将类型(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;
}
调用:
GetValueByKey<string>("aaa");
GetValueByKey<int>("bbb");
参考:http://stackoverflow.com/questions/8171412/cannot-implicitly-convert-type-int-to-t
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
相关文章推荐
- MLN 讨论 —— inference
- javascript发送短信验证码实现代码
- Service
- 全文索引 Lucene初探
- 医药采购之供货商药品目录添加提交
- C语言高频面试题之sizeof与指针和结构体专题总结
- uboot1.1.6/lowlevel.S详解
- Redis配置文件参数说明
- How to use umdh to check Windows memory leak
- svn的备份还原(一)
- Android Process 进程通信(一)
- Windows文件和文件夹定期清理
- Android4.2 第一次开机引导界面
- 活动h5页面倒计时效果
- 安装
- windows server 2012 standard eval评估板过期-解决方法
- MVC 带扩展名的路由无法访问
- Ceph-0.9.0 源码安装
- vi 编辑器常用命令
- 诗意回文