什么是正确的替代静态方法继承?静态、正确、方法

2023-09-02 01:29:13 作者:白露饮尘霜

我的理解是静态方法的继承,不支持在C#。我也看过一些讨论(包括在这里),其中开发人员声称需要此功能,对此,典型的反应是:如果你需要的静态成员的继承,有一个在你的设计缺陷的。

I understand that static method inheritance is not supported in C#. I have also read a number of discussions (including here) in which developers claim a need for this functionality, to which the typical response is "if you need static member inheritance, there's a flaw in your design".

确定,因为OOP不希望我就别想静态继承,我必须得出结论,我为它显然需要指出我的设计错误。但是,我坚持。我真的AP preciate一些帮助解决这一点。这里的挑战......

OK, given that OOP doesn't want me to even think about static inheritance, I must conclude that my apparent need for it points to an error in my design. But, I'm stuck. I would really appreciate some help resolving this. Here's the challenge ...

我想创建一个抽象基类(姑且称之为一种水果),它封装了一些复杂的初始化code。这code不能放置在构造函数中,因为它的一些将依赖于虚拟方法调用。

I want to create an abstract base class (let's call it a Fruit) that encapsulates some complex initialization code. This code cannot be placed in the constructor, since some of it will rely on virtual method calls.

水果会被其他具体类(苹果,橙),每个都必须公开一个标准的工厂方法CreateInstance()创建和初始化实例继承。

Fruit will be inherited by other concrete classes (Apple, Orange), each of which must expose a standard factory method CreateInstance() to create and initialize an instance.

如果静态成员的继承是可行的,我会放置在基类中的工厂方法,并使用虚拟方法调用派生类,以从一个具体的实例必须被初始化的类型。客户端code将简单的调用Apple.CreateInstance(),以获得一个完全初始化苹果实例。

If static member inheritance were feasible, I would place the factory method in the base class and use a virtual method call to the derived class to obtain the type from which a concrete instance must be initialized. The client code would simple invoke Apple.CreateInstance() to obtain a fully initialized Apple instance.

但显然这是不可能的,所以可以有人请解释如何我的设计需要改变,以适应相同的功能。

But clearly this is not possible, so can someone please explain how my design needs to change to accommodate the same functionality.

推荐答案

一个想法:

public abstract class Fruit<T>
    where T : Fruit<T>, new()
{
    public static T CreateInstance()
    {
        T newFruit = new T();
        newFruit.Initialize();  // Calls Apple.Initialize
        return newFruit;
    }

    protected abstract void Initialize();
}

public class Apple : Fruit<Apple>
{
    protected override void Initialize() { ... }
}

和调用,像这样:

Apple myAppleVar = Fruit<Apple>.CreateInstance();

没有多余的工厂类需要。

No extra factory classes needed.

 
精彩推荐