Skip to main content
 首页 » 编程设计

c#之设置隐藏基类的属性

2024年02月06日13shanyou

我有以下代码:

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 }); 
    } 
}