gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:06:46 25 4
gpt4 key购买 nike

例如我有两个类,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.

关于c# - 继承 : possible to change base reference to something else?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8161033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com