How to get the default value of an object property? [duplicate]

人走茶凉 提交于 2019-12-11 03:51:49

问题


Some code:

foreach (System.Reflection.PropertyInfo pi in myObject.GetType().GetProperties())
{
    if (pi.CanWrite)
    {
        object value = pi.GetValue(Properties, null);

        // if (value is not default)
        // {
        X.addAttribute(pi.Name, value);
        // }
    }
}

What I'm trying to do is not-call the line 'X.addAttribute...' if the property is at its DefaultValue. I assume there's some way of getting the DefaultValue of a property so I can do a comparison?

For my purpose I am trying to get the 'default' value as defined by DefaultValueAttribute.

Any help is appreciated, cheers.


回答1:


Assuming you're trying to get the DefaultValue attribute, use GetCustomAttributes on your PropertyInfo objects.




回答2:


Below is the method I use to get a default value of any runtime-type it will return 'null' for non value types otherwise it will return the default value type (it includes caching of value types for extra perf):

private static readonly Dictionary<Type, object> DefaultValueTypes 
    = new Dictionary<Type, object>();

public static object GetDefaultValue(Type type)
{
    if (!type.IsValueType) return null;

    object defaultValue;
    lock (DefaultValueTypes)
    {
        if (!DefaultValueTypes.TryGetValue(type, out defaultValue))
        {
            defaultValue = Activator.CreateInstance(type);
            DefaultValueTypes[type] = defaultValue;
        }
    } 

    return defaultValue;
}



回答3:


First, You must always initialize the field with value you want as a default.

Something similar

    class UnitManager
    {
      private int value;

      [DefaultValue("0")]
      public int Value
      {
       get { return this.value; }
       set { this.value = value; } 
      }
    } 

Then simply use

    UnitManager manager = new UnitManager()

    int startValue = manager.Value;


来源:https://stackoverflow.com/questions/2272469/how-to-get-the-default-value-of-an-object-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!