日期:2014-05-19  浏览次数:20824 次

关于泛型方法问题-如何通过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);
}
}