读书人

关于泛型方法有关问题-怎么通过T的类型

发布时间: 2012-01-19 00:22:27 作者: rapoo

关于泛型方法问题-如何通过T的类型和Text值返回该类型的值
如何通过T的类型和Text值返回该类型的值

例如:getValue <DateTime?> ( "2007-5-14 ") 返回日期类型的值;
getValue <int?> ( "5 ") 返回整形的值5;

public static T getValue <T> (string strText)
{
T t1 = default(T);

if (strText != " ")
{
// 需要实现的代码
}

return t1;
}

[解决办法]
晕~
[解决办法]
我是这样做的
return (T)Convert.ChangeType(strText,typof(T));
[解决办法]
class Program
{
public static T GetValue <T> (string strText) //方法名规范应该大写开头
{
T t1 = default(T);

if (strText != " ")
{
return (T)Convert.ChangeType(strText, typeof(T));//楼上少一个e
}

return t1;
}

static void Main(string[] args)
{
DateTime d = GetValue <DateTime> ( "2007-5-14 ");
Console.WriteLine(d);
int i = GetValue <int> ( "5 ");
Console.WriteLine(i);
}
}

读书人网 >C#

热点推荐