我有一个从基类 (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);
}
}
我的问题是这样的。在Process方法中,是否可以弄清楚对象到底是什么(Descendant1),然后声明该类型的对象(可能使用Reflection)并将BaseClass参数转换为它,然后进行反射杂技吗?
谢谢。
最佳答案
我不确定我是否理解你的问题,但也许你正在考虑这样的事情:
public string Process(BaseClass bc, string propertyName)
{
PropertyInfo property = bc.GetType().GetProperty(propertyName);
return (string)property.GetValue(bc, null);
}
bc.GetType() 获取 bc 的真实类型(当您传递 Descendant1 时,它将是 Descendant1 而不是 BaseClass)。
关于c# - 如何获取后代类的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/466352/