如何通过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;
    }

解决方案 »

  1.   

    通过判断T的类型,然后用Convert进行转换,可以实现,不过感觉比较繁琐,不知道是否有更简洁的做法
      

  2.   

    我是这样做的
    return (T)Convert.ChangeType(strText,typof(T));
      

  3.   

    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);
        }
    }