我有以下代码:
public class Ancestor
{
public string Property {get; protected set;}
}
public class Base : Ancestor
{
public string Property {get; set;}
}
public class Derived : Base
{
public Derived(string message)
{
//I need both properties to have the message value
}
}
Ancestor 和 Base 类不是我的代码,我无法更改它们。
有什么办法可以设置Ancestor的属性为message的值吗?
显然简单地做类似下面的事情是行不通的
Ancestor ancestor = this;
ancestor.Property = message
因为 setter 是 protected 。
请您参考如下方法:
仅通过反射:
public class Derived : Base
{
public Derived(string message)
{
Type type = typeof(Ancestor);
Ancestor a = (Ancestor)this;
type.GetProperty("Property").SetMethod.Invoke(a, new[] { message });
}
}
