[英]Get property value from string using reflection in C# - problem with inherited class
I have a class Cinherited which inherits from class Cbase . 我有一个类Cinherited从类CBase的继承。
When I attempt to list the properties for class Cinherited , using reflection, it only returns the properties for the base class, Cbase . 当我尝试使用反射列出Cinherited类的属性时,它仅返回基类Cbase的属性。
Here is the (somewhat simplified) code that demonstrates the problem: 这是演示问题的(略有简化)代码:
public class Cinherited: Cbase
{
public int x;
public void printProperties()
{
Type t = this.GetType();
PropertyInfo[] pi = t.GetProperties();
foreach (PropertyInfo prop in pi)
{
// ERROR: Next line only prints properties in base class Cbase.
Console.Write("Prop: {0}: {1}\n", prop.Name, prop.GetValue(this,null));
}
}
}
It looks like you've declared fields rather than properties on your derived class. 看起来您已经声明了字段而不是派生类的属性。 You can use code like this to access them:
您可以使用如下代码来访问它们:
public void PrintField()
{
Type t = this.GetType();
FieldInfo[] fi = t.GetFields();
foreach (FieldInfo field in fi)
{
Console.Write("Field: {0}: {1}\n", field.Name, prop.GetValue(this));
}
}
You can set the value of this field by calling SetValue()
: 您可以通过调用
SetValue()
来设置此字段的值:
field.SetValue(this, -1);
Properties should be defined as 属性应定义为
public int x {get; set;}
But this is a public field: 但这是一个公共领域:
public int x;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.