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

后端 未结 6 1156
不知归路
不知归路 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 02:05

    if (typeof(T).IsValueType || typeof(T) == typeof(String))
    {
         return default(T);
    }
    else
    {
         return Activator.CreateInstance();
    }
    

    Untested, but the first thing that came to mind.

提交回复
热议问题