获取类成员的默认值 [英] Get default value of class member
本文介绍了获取类成员的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个ClassWithMember类
Let's assume I have a class ClassWithMember
class ClassWithMember
{
int myIntMember = 10;
}
如何通过System.Type获取myIntMember成员的默认值10?
How do I get the default value 10 of the myIntMember member by System.Type?
我目前正在苦苦挣扎的思考是int的默认值(0)而不是类的默认成员(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)..
推荐答案
您可以尝试执行以下操作:
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.
这篇关于获取类成员的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文