Best way to test if a generic type is a string? (C#)

后端 未结 6 1169
不知归路
不知归路 2020-12-13 01:09

I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type

6条回答
  •  孤街浪徒
    2020-12-13 01:49

    Personally, I like method overloading:

    public static class Extensions { 
      public static String Blank(this String me) {      
        return String.Empty;
      }
      public static T Blank(this T me) {      
        var tot = typeof(T);
        return tot.IsValueType
          ? default(T)
          : (T)Activator.CreateInstance(tot)
          ;
      }
    }
    class Program {
      static void Main(string[] args) {
        Object o = null;
        String s = null;
        int i = 6;
        Console.WriteLine(o.Blank()); //"System.Object"
        Console.WriteLine(s.Blank()); //""
        Console.WriteLine(i.Blank()); //"0"
        Console.ReadKey();
      }
    }
    

提交回复
热议问题