[英]Get property value from string using reflection in C# - problem with inherited class
我有一個類Cinherited從類CBase的繼承。
當我嘗試使用反射列出Cinherited類的屬性時,它僅返回基類Cbase的屬性。
這是演示問題的(略有簡化)代碼:
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));
}
}
}
看起來您已經聲明了字段而不是派生類的屬性。 您可以使用如下代碼來訪問它們:
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));
}
}
您可以通過調用SetValue()
來設置此字段的值:
field.SetValue(this, -1);
屬性應定義為
public int x {get; set;}
但這是一個公共領域:
public int x;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.