0

我有一个通用的方法。

private T Blah<T>()

在这种方法中,我有一个要返回的字符串,但问题是它T可能不是字符串。值T可以是stringintDateTimeDateTime?decimal?

我该如何处理这个字符串,以便我可以返回它并支持所有这些类型?

4

3 回答 3

4
  private T Blah<T> () where T : IConvertible
  {            
     if (!String.IsNullOrEmpty(source))
          return (T)Convert.ChangeType(source, typeof(T));
     return default(T);
  }

应该适用于所有这些类型。

于 2013-03-30T02:45:16.853 回答
1

这可能会有所帮助:

private T Blah<T>(Func<string, T> map)
{   
    //Your codes here

    return map(yourString); //yourString: the string which you are going to convert
}

在这里你称之为:

//For int
Blah(input => int.Parse(input));

//For DateTime
Blah(input => DateTime.Parse(input));
于 2013-03-30T03:05:45.780 回答
1

Blah<T> 公开测试,根据您的要求进行修改。

  • 代码

    partial class SomeClass {
        public T Blah<T>() {
            var t="2013 03 30";
    
            return (T)(typeof(String).Equals(typeof(T))?t as object:(
                from args in new[] { new object[] { t, default(T) } }
                let type=Nullable.GetUnderlyingType(typeof(T))??typeof(T)
                let types=new[] { typeof(String), type.MakeByRefType() }
                let bindingAttr=BindingFlags.Public|BindingFlags.Static
                let tryParse=type.GetMethod("TryParse", bindingAttr, default(Binder), types, null)
                let b=typeof(DateTime)!=type
                let dummy=b?args[0]=((String)args[0]).Split('\x20').Aggregate(String.Concat):""
                let success=null!=tryParse?tryParse.Invoke(typeof(T), args):false
                select args.Last()).Last());
        }
    }
    

    partial class TestClass {
        public static void TestMethod() {
            var x=new SomeClass();
    
            Console.WriteLine("x.Blah<String>() = {0}", x.Blah<String>());
            Console.WriteLine("x.Blah<int>() = {0}", x.Blah<int>());
            Console.WriteLine("x.Blah<DateTime>() = {0}", x.Blah<DateTime>());
            Console.WriteLine("x.Blah<DateTime?>() = {0}", x.Blah<DateTime?>());
            Console.WriteLine("x.Blah<decimal?>() = {0}", x.Blah<decimal?>());
        }
    }
    
  • 输出

    x.Blah<String>() = 2013 03 30
    x.Blah<int>() = 20130330
    x.Blah<日期时间>() = 2013/3/30 0:00:00
    x.Blah<DateTime?>() = 2013/3/30 0:00:00
    x.Blah<十进制?>() = 20130330
    

The special thing is that I removed the spaces if destination type is not DateTime or DateTime?.

You can even try with x.Blah<long>() which is not in your requirement, and any other types. Let me know if you found any type can cause an exception.

于 2013-03-30T06:02:39.397 回答