简体   繁体   English

如何强制子类实现一个方法

[英]How to force sub classes to implement a method

I am creating an object structure and I want all sub classes of the base to be forced to implement a method. 我正在创建一个对象结构,我希望强制基类的所有子类实现一个方法。

The only ways I could think of doing it were: 我能想到的唯一方法是:

  1. An abstract class - Would work but the base class has some useful helper functions that get used by some of the sub classes. 一个抽象类 - 可以工作,但基类有一些有用的辅助函数,可供一些子类使用。

  2. An interface - If applied to just the base class then the sub classes don't have to implement the function only the base class does. 接口 - 如果仅应用于基类,则子类不必仅实现基类所具有的功能。

Is this even possible? 这甚至可能吗?

NB This is a .NET 2 app. 注意这是一个.NET 2应用程序。

You can have abstract methods in a class with other methods that are implemented. 您可以在类中使用其他方法实现抽象方法。 The advantage over an interface is that you can include some code with your class and have the new object be forced to fill in the details for the abstract methods. 相对于接口的优点是,您可以在类中包含一些代码,并强制新对象填写抽象方法的详细信息。

public abstract class YourClass
{
    // Your class implementation

    public abstract void DoSomething(int x, int y);

    public void DoSomethingElse(int a, string b)
    {
        // You can implement this here
    }
}

An interface - If applied to just the base class then the sub classes don't have to implement the function only the base class does. 接口 - 如果仅应用于基类,则子类不必仅实现基类所具有的功能。

This is not entirely correct. 这不完全正确。 If the base class is abstract, you can mark methods that belong to the interface as abstract, and force the implementation in the subclasses. 如果基类是抽象的,则可以将属于该接口的方法标记为抽象,并强制实现子类。

That brings an option you didn't mention: to use both. 这带来了你没有提到的选项:同时使用两者。 You have an IFoo interface, and a FooBase abstract base class the implements it, or part of it. 你有一个IFoo接口,一个FooBase抽象基类实现它,或者它的一部分。 This provides subclasses with a "default" implementation of the interface (or part of it), and also lets you inherit from something else and still implement the interface, or if you want to implement the interface but not inherit the base class implementation. 这为子类提供了接口(或其一部分)的“默认”实现,并且还允许您继承其他内容并仍然实现接口,或者如果要实现接口但不继承基类实现。 An example might help: 一个例子可能有帮助:

// Your interface
interface IFoo { void A(); void B; }

// A "default" implementation of that interface
abstract class FooBase : IFoo
{
    public abstract void A();

    public void B()
    {
        Console.WriteLine("B");
    }
}

// A class that implements IFoo by reusing FooBase partial implementation
class Foo : FooBase
{
    public override void A()
    {
        Console.WriteLine("A");
    }
}

// This is a different class you may want to inherit from
class Bar
{
    public void C()
    {
        Console.WriteLine("C");
    }
}

// A class that inherits from Bar and implements IFoo
class FooBar : Bar, IFoo
{
    public void A()
    {
        Console.WriteLine("Foobar.A");
    }
    public void B()
    {
        Console.WriteLine("Foobar.B");
    }
}

An abstract class - Would work but the base class has some useful helper functions that get used by some of the sub classe 一个抽象类 - 可以工作,但基类有一些有用的辅助函数,可供一些子classe使用

An abstract class doesn't require all functions it provides to be abstract. 抽象类不要求它提供的所有函数都是抽象的。

abstract class Base {
    public void Foo() {} // Ordinary method
    public virtual void Bar() {} // Can be overridden
    public abstract void Xyz(); // This one *must* be overridden
}

Note that if you replace public with protected , the marked method will be only visible to base classes and subclasses. 请注意,如果将public替换为protected ,则标记的方法仅对基类和子类可见。

Yes, and if all the classes you need to do this for are logically subclasses of an existing abstract base class, then add an abstract method to the base class... This is better than an interface because it allows you to add implementation later (by changing abstract base class method to virtual method with a default implementation), if/when it turns out that, say, eight of ten derived classes will have the same implementation, and say, only two of them differ... 是的,如果您需要执行此操作的所有类都是现有抽象基类的逻辑子类,则将抽象方法添加到基类...这比接口更好,因为它允许您稍后添加实现(通过使用默认实现将抽象基类方法更改为虚方法),如果/当发现,例如,十个派生类中的八个将具有相同的实现,并且说,它们中只有两个不同...

EDIT: (based on thread in comments below) The base class must be declared as abstract to do this... You can't have an abstract method in a non-abstract class because a non-abstract class can be instantiated, and if an instance of it was created, there wouldbe NO implementation for that method. 编辑:(基于以下评论中的线程)基类必须声明为抽象来执行此操作...您不能在非抽象类中使用抽象方法,因为可以实例化非抽象类,如果创建了它的一个实例,该方法没有实现。 So this is illegal. 所以这是非法的。 By declaring the base as abstract, you inhibit instantiation of the class. 通过将基数声明为抽象,可以禁止对类进行实例化。 Then, only non-abstract derived classes can be instantiated, where, (because the base method is abstract) you MUST add an implementation for that method. 然后,只能实例化非抽象派类,其中,(因为基本方法是抽象的)你必须为该方法添加一个实现。

And full worker sample with params (.netcore 2.2): 和完整的工人样本与params(.netcore 2.2):

class User{
    public string Name = "Fen";
}

class Message{
    public string Text = "Ho";
}

// Interface
interface IWorkerLoop
{
    // Working with client message
    string MessageWorker(string msg);
}

// AbstractWorkerLoop partial implementation
public abstract class AbstractWorkerLoop : IWorkerLoop
{
    public User user;
    public Message msg;

    // Append session object to loop
    public abstract AbstractWorkerLoop(ref User user, ref Message msg){
        this.user = user;
        this.msg = msg;
    }

    public abstract string MessageWorker(string msg);
}

// Worker class
public class TestWorkerLoop : AbstractWorkerLoop
{
    public TestWorkerLoop(ref User user, ref Message msg) : base(user, msg){
        this.user = user;
        this.msg = msg;
    }

    public override string MessageWorker(string msg){
        // Do something with client message    
        return "Works";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM