C# 如何强制子类实现一个方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1771741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to force sub classes to implement a method
提问by tgandrews
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:
我能想到的唯一方法是:
An abstract class - Would work but the base class has some useful helper functions that get used by some of the sub classes.
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?
这甚至可能吗?
N.B. This is a .NET 2 app.
注意这是一个 .NET 2 应用程序。
采纳答案by Kelsey
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
}
}
回答by Charles Bretana
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 derivedclasses can be instantiated, where, (because the base method is abstract) you MUST add an implementation for that method.
编辑:(基于下面评论中的线程)必须将基类声明为抽象来执行此操作...您不能在非抽象类中使用抽象方法,因为可以实例化非抽象类,并且如果创建了它的一个实例,该方法将没有实现。所以这是非法的。通过将基类声明为抽象类,您可以禁止类的实例化。然后,只能实例化非抽象派生类,其中(因为基方法是抽象的)您必须为该方法添加一个实现。
回答by Dario
An abstract class - Would work but the base class has some useful helper functions that get used by some of the sub 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 onlyvisible to base classes and subclasses.
请注意,如果您替换public
为protected
,则标记的方法将仅对基类和子类可见。
回答by R. Martinho Fernandes
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. 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:
这带来了一个您没有提到的选项:两者都使用。您有一个IFoo
接口和一个FooBase
实现它的抽象基类,或者它的一部分。这为子类提供了接口(或其一部分)的“默认”实现,并且还允许您从其他东西继承并仍然实现接口,或者如果您想实现接口但不继承基类实现。一个例子可能会有所帮助:
// 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");
}
}
回答by WorksIt
And full worker sample with params (.netcore 2.2):
以及带有参数的完整工作示例(.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";
}
}