将字符串转换为T.

时间:2014-02-16 05:33:20

标签: c# generics type-conversion

我有一个方法需要将字符串转换为泛型类型:

T GetValue<T>(string name)
{
   string item = getstuff(name);
   return item converted to T   // ????????
}

T可以是int或date。

1 个答案:

答案 0 :(得分:12)

您可以使用Convert.ChangeType

T GetValue<T>(string name)
{
   string item = getstuff(name);
   return (T)Convert.ChangeType(item, typeof(T));
}

如果您只需要为int和DateTime限制输入类型,请添加如下所示的条件

if (typeof(T) != typeof(int) && typeof(T) != typeof(DateTime))
{
     // do something with other types 
}