循环继承以获取重写的属性
Looping up inheritance to get overridden properties
考虑以下 类
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) 并因此获得两个唯一的字符串
应该这样做:
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");
}
您应该能够使用此方法构建一个方法来执行您想要的操作。
考虑以下 类
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) 并因此获得两个唯一的字符串
应该这样做:
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");
}
您应该能够使用此方法构建一个方法来执行您想要的操作。