Programmatic equivalent of default(Type)

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

    I do the same task like this.

    //in MessageHeader 
       private void SetValuesDefault()
       {
            MessageHeader header = this;             
            Framework.ObjectPropertyHelper.SetPropertiesToDefault(this);
       }
    
    //in ObjectPropertyHelper
       public static void SetPropertiesToDefault(T obj) 
       {
                Type objectType = typeof(T);
    
                System.Reflection.PropertyInfo [] props = objectType.GetProperties();
    
                foreach (System.Reflection.PropertyInfo property in props)
                {
                    if (property.CanWrite)
                    {
                        string propertyName = property.Name;
                        Type propertyType = property.PropertyType;
    
                        object value = TypeHelper.DefaultForType(propertyType);
                        property.SetValue(obj, value, null);
                    }
                }
        }
    
    //in TypeHelper
        public static object DefaultForType(Type targetType)
        {
            return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
        }
    

提交回复
热议问题