Programmatic equivalent of default(Type)

前端 未结 14 1801
时光取名叫无心
时光取名叫无心 2020-11-22 05:28

I\'m using reflection to loop through a Type\'s properties and set certain types to their default. Now, I could do a switch on the type and set the defau

14条回答
  •  野性不改
    2020-11-22 06:30

    • In case of a value type use Activator.CreateInstance and it should work fine.
    • When using reference type just return null
    public static object GetDefault(Type type)
    {
       if(type.IsValueType)
       {
          return Activator.CreateInstance(type);
       }
       return null;
    }
    

    In the newer version of .net such as .net standard, type.IsValueType needs to be written as type.GetTypeInfo().IsValueType

提交回复
热议问题