小技巧(累积)-反射读取资源、ToString()不抛出异常
string langPreference = Session["LanguagePreference"] as string;
一、功能:通过反射取静态属性的值
目的:通过错误码,动态的从资源文件中找到各语种的资源。
public string GetErrInfo(int errCode)
{
string resourceKey;
if(errCode>=0)
{
resourceKey="R"+errCode.ToString();
}
else
{
errCode=errCode*-1;
resourceKey="R_"+errCode.ToString();
}
Type t = typeof(Resources.Login);
PropertyInfo pi = t.GetProperty(resourceKey);
return pi.GetValue(null, null).ToString();
}
如果不用反射,而使用swich,则会写很多重复代码,资源文件更新时,读取资源的方法也要改变,如增加,删除case语句。{
string resourceKey;
if(errCode>=0)
{
resourceKey="R"+errCode.ToString();
}
else
{
errCode=errCode*-1;
resourceKey="R_"+errCode.ToString();
}
Type t = typeof(Resources.Login);
PropertyInfo pi = t.GetProperty(resourceKey);
return pi.GetValue(null, null).ToString();
}
public string GetErrInfo(int errCode)
{
string resourceKey;
string resourceName="";
if(errCode>=0)
{
resourceKey="R"+errCode.ToString();
}
else
{
errCode=errCode*-1;
resourceKey="R_"+errCode.ToString();
}
switch(resourceKey)
{
case "R299":
resourceName= Resources.Login.R299;
break;
case "R300":
resourceName= Resources.Login.R300;
break;
case "R301":
resourceName = Resources.Login.R301;
break;
case "R304":
resourceName = Resources.Login.R304;
break;
case "R303":
resourceName = Resources.Login.R303;
break;
}
return resourceName;
}
二、功能:object转换成string时不抛出异常{
string resourceKey;
string resourceName="";
if(errCode>=0)
{
resourceKey="R"+errCode.ToString();
}
else
{
errCode=errCode*-1;
resourceKey="R_"+errCode.ToString();
}
switch(resourceKey)
{
case "R299":
resourceName= Resources.Login.R299;
break;
case "R300":
resourceName= Resources.Login.R300;
break;
case "R301":
resourceName = Resources.Login.R301;
break;
case "R304":
resourceName = Resources.Login.R304;
break;
case "R303":
resourceName = Resources.Login.R303;
break;
}
return resourceName;
}
目的:如果object是null则转换为null
下面的代码如果Session["LanguagePreference"] 为null转换为string时抛出异常。tostring会试图把
null转换为“”。
string langPreference = Session["LanguagePreference"].ToString();
修改为下面的代码就不会有异常了langPreference的值为null string langPreference = Session["LanguagePreference"] as string;
* as string 只是判断是否是string类型,并不会转型,而.toString 可以,如果用到类型转换时,就必须用ToString了