您的位置:首页 > 其它

将类型(int,string,…)转换为 T 类型

2015-11-12 09:47 375 查看
方法定义:

privatestaticTGetValueByKey<T>(stringkey)whereT:IConvertible
{
TlocalVal=default(T);

stringstrType=typeof(T).Name;
stringvaluesData=ConfigurationManager.AppSettings[key].ToString();

localVal=(T)Convert.ChangeType(valuesData,typeof(T));

returnlocalVal;

}

publicstaticTConvertTypeDoConvert<TConvertType>(objectconvertValue,outboolhasConverted)
{
hasConverted=false;
varconverted=default(TConvertType);
try
{
converted=(TConvertType)
Convert.ChangeType(convertValue,typeof(TConvertType));
hasConverted=true;
}
catch(InvalidCastException)
{
}
catch(ArgumentNullException)
{
}
catch(FormatException)
{
}
catch(OverflowException)
{
}

returnconverted;
}

写法二:


publicstaticTConvertTypeDoConvert<TConvertType>(objectconvertValue,outboolhasConverted)
{
hasConverted=false;
varconverted=default(TConvertType);
try
{
converted=(TConvertType)
Convert.ChangeType(convertValue,typeof(TConvertType));
hasConverted=true;
}
catch(InvalidCastException)
{
}
catch(ArgumentNullException)
{
}
catch(FormatException)
{
}
catch(OverflowException)
{
}

returnconverted;
}



调用:

GetValueByKey<string>("aaa");

GetValueByKey<int>("bbb");

参考:http://stackoverflow.com/questions/8171412/cannot-implicitly-convert-type-int-to-t
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: