简体   繁体   English

获取类成员的默认值

[英]Get default value of class member

Let's assume I have a class ClassWithMember 我们假设我有一个ClassWithMember类

class ClassWithMember
{
    int myIntMember = 10;
}

How do I get the default value 10 of the myIntMember member by System.Type? 如何通过System.Type获取myIntMember成员的默认值10?

I'm currently struggling around with reflections by all I retreive is the default value of int (0) not the classes default member (10).. 我目前正在努力解决所有我的反思是int(0)的默认值而不是类默认成员(10)..

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. 这里的技巧是实例化一个实例。

尝试创建一个实例,用反射来检索值。

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 . 如果您控制ClassWithMember的代码,则可以使用System.ComponentModel[DefaultValue]属性采用完全不同的方法。 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. 现在,您可以使用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. 请记住,由于Reflection要求,这将变得非常慢,所以如果这个代码被大量实例化,你可能想要找到一个不同的方法。 Also, it won't work with non-value types, due to a limitation with the .NET Framework's attribute support. 此外,由于.NET Framework的属性支持的限制,它不适用于非值类型。

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. 您仍然可以使用Activator.CreateInstance创建MonoBehaviour / ScriptableObject并检查其值,如果它只是为了检查默认值。 Make sure to use DestroyImmediate afterwards ;-) 确保之后使用DestroyImmediate ;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM