Get default value of class member

后端 未结 4 1308
灰色年华
灰色年华 2020-12-16 05:56

Let\'s assume I have a class ClassWithMember

class ClassWithMember
{
    int myIntMember = 10;
}

How do I get the default value 10 of the m

相关标签:
4条回答
  • 2020-12-16 06:17

    You can try something like this:

    var field = typeof(ClassWithMember).GetField("myIntMember",
        BindingFlags.Instance | BindingFlags.NonPublic);
    var value = (int)field.GetValue(new ClassWithMember());
    

    The trick here is to instantiate an instance.

    0 讨论(0)
  • 2020-12-16 06:24

    If you're in control of the code for ClassWithMember, you could take a completely different approach to this by using the [DefaultValue] attribute from System.ComponentModel. Basically, what you'd do is write something like this:

    class ClassWithMember
    {
        public ClassWithMember()
        {
            SetDefaultValues();
        }
    
        [DefaultValue(5)]
        public MyIntMember { get; set; }
    }
    

    And then have a function like this somewhere, perhaps in a base class:

    public void SetDefaultValues()
    {
        foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(this))
        {
            DefaultValueAttribute a = prop.Attributes[typeof(DefaultValueAttribute)] as DefaultValueAttribute;
            if (a == null) 
                continue;
            prop.SetValue(this, a.Value);
        }
    }
    

    So now, you have a situation where you can easily retrieve the default values using Reflection.

    Keep in mind that this is going to be quite a lot slower due to the Reflection requirement, so if this code gets instantiated a lot, you'll probably want to find a different approach. Also, it won't work with non-value types, due to a limitation with the .NET Framework's attribute support.

    0 讨论(0)
  • 2020-12-16 06:28

    Try creating an instance an retreive the value with reflection.

    0 讨论(0)
  • 2020-12-16 06:30

    You can still use Activator.CreateInstance to create a MonoBehaviour/ScriptableObject and check its values, if it's simply for the sake of checking the default Values. Make sure to use DestroyImmediate afterwards ;-)

    0 讨论(0)
提交回复
热议问题