考虑以下课程
public class Super
{
public abstract string Foo { get; }
}
public class Base : Super
{
public override string Foo { get { return "Foo"; } }
}
public class Sub : Base
{
public override string Foo { get { return "Bar"; } }
}
我怎么能知道Sub的类型和Foo的PropertyInfo,循环遍历Foo的两个声明来调用PropertInfo.GetValue(this),从而得到两个唯一的字符串
答案 0 :(得分:1)
这应该这样做:
public class baseType
{
public string P { get { return "A"; }}
}
public class child : baseType
{
new public string P { get { return "B"; }}
}
public static object GetBasePropValue(object src, string propName)
{
return src.GetType().BaseType.GetProperty(propName).GetValue(src, null);
}
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
void Main()
{
var x = GetPropValue(new child(), "P");
var y = GetBasePropValue(new child(), "P");
}
你应该能够使用这种方法构建一个方法来做你想做的事。