C# 如何从基类调用派生类方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16088799/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:58:11  来源:igfitidea点击:

How do I call a derived class method from the base class?

c#derived-classbase-class

提问by CramerTV

I have read several similar questions about this but none seem to solve the problem I am facing. The typical answer is to cast as the derived class but I cannot since I do not know the derived class type.

我已经阅读了几个关于此的类似问题,但似乎没有一个能解决我面临的问题。典型的答案是强制转换为派生类,但我不能,因为我不知道派生类类型。

Here is my example:

这是我的例子:

class WireLessDevice { // base class
    void websocket.parsemessage(); // inserts data into the wireless device object
}

class WiFi : WireLessDevice { // derived class
    GPSLoc Loc;
}

Wireless Device can also be derived to make Bluetooth, Wi-Max, Cellular, etc. devices and thus I do not know which type of wirelessdevice will be receiving the data.

也可以派生出无线设备来制作蓝牙、Wi-Max、蜂窝等设备,因此我不知道哪种类型的无线设备将接收数据。

When a GPS packet is received on the websocket in the base class I need to update the derived device's location.

当在基类中的 websocket 上接收到 GPS 数据包时,我需要更新派生设备的位置。

I thought perhaps sending a message via a queue or creating an event handler and sending the location in the event arguments but those seem a little clunky when the data is staying within the class.

我想也许通过队列发送消息或创建事件处理程序并在事件参数中发送位置,但是当数据保留在类中时,这些看起来有点笨拙。

Is there something built into the language that would allow me to call my derived device from the base class without knowing the type?

语言中是否有内置的东西可以让我在不知道类型的情况下从基类调用我的派生设备?

采纳答案by omer schleifer

The correct way is to add a method DoSomeMagic() in the base class, with default implementation, or abstract. The derived class should than override it to do its magic.

正确的方法是在基类中添加一个方法DoSomeMagic(),默认实现,或者抽象。派生类应该覆盖它来发挥它的魔力。

Something like this maybe:

可能是这样的:

public class WireLessDevice
{ // base class
    protected virtual void ParseMessage()
    {
        // Do common stuff in here
    }
}

public class WiFi : WireLessDevice
{ // derived class
    override void ParseMessage()
    {
        base.ParseMessage();//Call this if you need some operations from base impl.
        DoGPSStuff();
    }
    private void DoGPSStuff()
    {
        //some gps stuff
    }
    GPSLoc Loc;
}

回答by Thorarin

Virtual methodswould be a good solution. You create a method ParseMessagein the base class which handles all the stuff common to each derived type, then override for specific devices.

虚拟方法将是一个很好的解决方案。您ParseMessage在基类中创建一个方法,该方法处理每个派生类型的所有通用内容,然后覆盖特定设备。

In order to still be able to handle other message types, you will need to call the base.ParseMessageas appropriate:

为了仍然能够处理其他消息类型,您需要base.ParseMessage适当地调用 :

class WireLessDevice
{
    protected virtual bool ParseMessage(byte[] message)
    {
        // Inspect message and handle the known ones
        return true; // Only if message parsed, otherwise false
    }
}

class WiFi : WireLessDevice
{
    GPSLoc Loc;

    protected override bool ParseMessage(byte[] message)      
    {
        bool messageParsed = base.ParseMessage(message)
        if (!messageParsed)
        {
            // Handle device specific message with GPSLoc
            Loc = ...
        }
        else
        {
            return false;
        }
    }
}

If your base class is not handling any other messages, the code could be simpler (and using abstract). However, in that case I would consider moving the web socket code to the derived class.

如果您的基类不处理任何其他消息,则代码可以更简单(并使用abstract)。但是,在这种情况下,我会考虑将 Web 套接字代码移动到派生类。