Programmatic equivalent of default(Type)

前端 未结 14 1907
时光取名叫无心
时光取名叫无心 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:16

    Equivalent to Dror's answer but as an extension method:

    namespace System
    {
        public static class TypeExtensions
        {
            public static object Default(this Type type)
            {
                object output = null;
    
                if (type.IsValueType)
                {
                    output = Activator.CreateInstance(type);
                }
    
                return output;
            }
        }
    }
    

提交回复
热议问题