Skip to main content
 首页 » 编程设计

c#之继承 : possible to change base reference to something else

2024年02月23日16pander-it

例如我有两个类,Base 和 Derived,如下所示:

class Base   
{         
    public string Name { get; set; } 
 
    public Base() 
    { 
 
    } 
} 
 
class Derived : Base 
{ 
    public Derived(Base b) 
    { 
        base = b; // doesn't compile, but is there any way to do something similar? 
    } 
}   

所以他们的行为是这样的:

Base b = new Base(); 
b.Name = "Bob"; 
Derived d = new Derived(b); 
d.Name = "John"; 
// b.Name is now "John" also 

这可能吗?我想一种方法是在 Derived 中保留 Base b 引用并覆盖 Derived.Name 以指向 b.Name?有没有更简单的方法,例如,如果我有 50 个属性要覆盖?

class Derived : Base 
{ 
    Base b; 
 
    public override string Name 
    { 
        get { return b.Name; } 
        set { b.Name = value; } 
    } 
 
    public Derived(Base b) 
    { 
        this.b = b; 
    } 
} 

编辑:

我猜另一种说法是我正在为类 Base 创建一种包装器。我得到了一个 Base 类型的对象,我想用类 Derived 包装它,但仍然保留 Base 的原始公共(public)属性/方法/等。我不确定这是否使它更清楚。

请您参考如下方法:

我认为从您似乎暗示的内容来看(至少从编辑 - “我正在为类 Base 创建一种包装器”),您正在考虑使用 Decorator 模式:

http://en.wikipedia.org/wiki/Decorator_pattern

The decorator pattern can be used to extend (decorate) the functionality of a certain object at run-time, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.