开发者

Get property value from string using reflection in C# - problem with inherited class

I have a class Cinherited which inherits from class Cbase.

When I attempt to list the properties for class Cinherited, using reflection, it only returns the properties for the base class, Cbase.

Here is the (somewhat simplified) code that demonstrates the problem:

public class Cinherited: Cbase
{
    public int x;

    public void printProperties()
    {
        Type t = this.Ge开发者_开发知识库tType();
        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():

field.SetValue(this, -1);


Properties should be defined as

public int x {get; set;}

But this is a public field:

public int x;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜