gpt4 book ai didi

c# - 强制继承者从其 CTOR (C#) 初始化基的字段

转载 作者:行者123 更新时间:2023-11-30 19:50:36 25 4
gpt4 key购买 nike

我试图强制抽象类的继承者初始化基类中的一个字段。

我无法通过基类中的构造函数执行此操作,因为字段的类型需要返回对创建它的对象的引用。 (我想我可以为字段类型提供一个无参数的 ctor。但我觉得这只会转移问题,而且无论如何它都应该是不可变的)。

也许有人可以建议如何去做,或者也许可以让我根本不需要做?

这几乎就是我正在做的:

public abstract class Base
{
// Would like to force setting in CTOR
protected BaseImplementation _implementation;
protected BaseImplementation Implementation
{ get { return _implementation; } }

public void DoSomething()
{
Implementation.DoSomething();
}
}

public abstract class BaseImplementation
{
public abstract void DoSomething();
}

public class MyObject : Base
{
// Note its Nested
public class MyImplementation : BaseImplementation
{
private MyObject _myObject;

public MyImplementation(MyObject myObject)
{
this._myObject = myObject;
}

public override void DoSomething()
{
// Does something
}
public virtual void SomethingElse()
{
// Does something else
}
}

new public MyImplementation Implementation
{
get { return (MyImplementation) _implementation; }
}

public void SomethingElse()
{
Implementation.SomethingElse();
}
}

为了提供一些背景信息,我有一些继承自基类的类。他们,实习生有多种方式可以操纵他们的状态。这是我想出的处理该问题的最佳解决方案。

编辑

我忘了说我没有使用抽象属性,因为这意味着我不能使用 new public MyImplementation Implementation {...。我不想在使用特定于派生类的功能时将 Implementation 强制转换为 MyImplementation (因此首先使用 new) 或创建包含同一个对象。

最佳答案

不要向基类添加字段。只需将其设为 abstract 属性即可。派生类必须重写它并返回它们自己的值。

protected abstract BaseImplementation Implementation { get; }

或者,您可以让基类构造函数接受类型为 BaseImplementation 的参数,并让派生类对其进行初始化:

public abstract class Base { 
protected Base(BaseImplementation implementation) {
_implementation = implementation;
}

private BaseImplementation _implementation;
protected BaseImplementation Implementation { get { return _implementation; } }
}

public class Derived : Base {
public Derived() : base(new MyImplementation()) { }
// ...
}

关于c# - 强制继承者从其 CTOR (C#) 初始化基的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2070378/

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