获取类成员的默认值
假设我有一个 ClassWithMember 类,
class ClassWithMember
{
int myIntMember = 10;
}
如何通过 System.Type 获取 myIntMember 成员的默认值 10?
我目前正在努力解决所有我检索到的反射,即 int (0) 的默认值而不是类默认成员 (10) ..
Let's assume I have a class ClassWithMember
class ClassWithMember
{
int myIntMember = 10;
}
How do I get the default value 10 of the myIntMember member by System.Type?
I'm currently struggling around with reflections by all I retreive is the default value of int (0) not the classes default member (10)..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以尝试这样的事情:
这里的技巧是实例化一个实例。
You can try something like this:
The trick here is to instantiate an instance.
尝试创建一个实例并通过反射检索值。
Try creating an instance an retreive the value with reflection.
如果您控制 ClassWithMember 的代码,则可以使用
System.ComponentModel
中的[DefaultValue]
属性,采取完全不同的方法。基本上,您要做的就是编写如下内容:然后在某处(也许在基类中)有一个类似的函数:
所以现在,您可以使用反射轻松检索默认值。
请记住,由于反射要求,这会慢很多,因此如果此代码被实例化很多,您可能需要找到一种不同的方法。此外,由于 .NET Framework 属性支持的限制,它不适用于非值类型。
If you're in control of the code for ClassWithMember, you could take a completely different approach to this by using the
[DefaultValue]
attribute fromSystem.ComponentModel
. Basically, what you'd do is write something like this:And then have a function like this somewhere, perhaps in a base class:
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.
如果只是为了检查默认值,您仍然可以使用 Activator.CreateInstance 创建 MonoBehaviour/ScriptableObject 并检查其值。确保事后使用 DestroyImmediate ;-)
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 ;-)