静态方法继承的正确替代方法是什么? [英] What's the correct alternative to static method inheritance?

查看:31
本文介绍了静态方法继承的正确替代方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 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 甚至不想让我考虑静态继承,我必须得出结论,我对它的明显需求指向了我设计中的一个错误.但是,我被困住了.我真的很感激一些帮助解决这个问题.这是挑战...

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 ...

我想创建一个抽象基类(我们称之为 Fruit),它封装了一些复杂的初始化代码.这段代码不能放在构造函数中,因为其中一些会依赖于虚方法调用.

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.

Fruit 将被其他具体类(Apple、Orange)继承,每个类都必须公开一个标准的工厂方法 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.

如果静态成员继承可行,我会将工厂方法放在基类中,并使用对派生类的虚方法调用来获取必须从中初始化具体实例的类型.客户端代码将简单地调用 Apple.CreateInstance() 以获取完全初始化的 Apple 实例.

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

不需要额外的工厂类.

这篇关于静态方法继承的正确替代方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆