如何获取后代类的属性值

Ang*_*ker 2 c# reflection inheritance

我有一个继承自基类(BaseClass)的类(Descendant1).将子类的实例传递给将BaseClass作为参数的方法.然后使用反射,它调用对象上的属性.

public class BaseClass { }

public class Descendant1 : BaseClass
{
    public string Test1 { get { return "test1"; } }
}


public class Processor
{
    public string Process(BaseClass bc, string propertyName)
    {
        PropertyInfo property = typeof(BaseClass).GetProperty(propertyName);
        return (string)property.GetValue(bc, null); 
    } 
}
Run Code Online (Sandbox Code Playgroud)

我的问题是这个.在Process方法中,是否有可能找出对象的真实位置(Descendant1),然后声明该类型的对象(可能使用Reflection)并将BaseClass参数强制转换为它,然后对其进行反射杂技?

谢谢.

emp*_*mpi 6

我不确定我是否理解你的问题,但也许你正在考虑这样的事情:

        public string Process(BaseClass bc, string propertyName)
        {
            PropertyInfo property =  bc.GetType().GetProperty(propertyName);
            return (string)property.GetValue(bc, null);
        }
Run Code Online (Sandbox Code Playgroud)

bc.GetType()获取实际类型的bc(当你传递Descendant1时,它将是Descendant1而不是BaseClass).