简体   繁体   English

继承一个重载方法

[英]Inheriting one overloaded method

I'm fairly new to C# and OOP, and I have a question in regards to inheritance. 我对C#和OOP还是比较陌生,关于继承我有一个问题。

Say I have: 说我有:

public abstract class Command
{
    protected Command()
    {
    }

    public abstract string Execute();

    public abstract string Execute(object o);
}

public class CommandA : Command
{
    public override string Execute()
    {
    }
}

public class CommandB : Command
{
    public override string Execute(object o)
    {
    }
}

There are obvious errors due to CommandA not implementing Execute(object o) and CommandB not implementing Execute() . 由于CommandA未实现Execute(object o)CommandB未实现Execute()因此存在明显的错误。

My question, then, is whether there is code I need to implement to avoid these errors? 那么,我的问题是是否需要执行代码来避免这些错误? Are empty methods allowed? 是否可以使用空方法?

You're abusing the use of abstract if you're expecting sub-classes to not actually implement some of the methods. 如果期望子类实际上未实现某些方法,则您正在滥用abstract abstract is used to enforce that the base class must implement the functionality. abstract用于强制基类必须实现功能。 What should happen if someone called new CommandB().Execute() ? 如果有人调用new CommandB().Execute()什么?

In some cases, a design may be incorrect and you end up in the situation you're in. In these cases, its somewhat common (though in my opinion a code smell), to do the following: 在某些情况下,设计可能是不正确的,并且最终导致您所处的情况。在这些情况下,它有些常见(尽管我认为有代码味),可以执行以下操作:

public class CommandA : Command
{
    public override string Execute()
    {
    }

    public override string Execute(object o)
    {
        throw new NotImplementedException();
    }
}

A somewhat cleaner approach: 一种更干净的方法:

public abstract class Command
{
    protected Command()
    {
    }

    public abstract string Execute(object o = null);
}

Though you're still going to have to deal with the fact that someone may pass an object to CommandA . 尽管您仍然需要处理有人可能将对象传递给CommandA的事实。

If the commands have such different behaviour, it's likely they shouldn't both be subclassing the same abstract class. 如果这些命令具有不同的行为,则很可能它们都不应该都属于同一抽象类。

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

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