[英]C#: How do I call a static method of a base class from a static method of a derived class?
[英]How do I call a derived class method from the base class?
我已经阅读了几个类似的问题,但似乎没有解决我面临的问题。 典型的答案是作为派生类进行转换,但我不能因为我不知道派生类类型。
这是我的例子:
class WireLessDevice { // base class
void websocket.parsemessage(); // inserts data into the wireless device object
}
class WiFi : WireLessDevice { // derived class
GPSLoc Loc;
}
还可以导出无线设备以制作蓝牙,Wi-Max,蜂窝等设备,因此我不知道哪种类型的无线设备将接收数据。
当在基类中的websocket上接收到GPS数据包时,我需要更新派生设备的位置。
我想也许可以通过队列发送消息或创建事件处理程序并在事件参数中发送位置,但是当数据停留在类中时,这些看起来有点笨拙。
是否有内置于该语言中的内容可以让我在不知道类型的情况下从基类调用我的派生设备?
正确的方法是在基类中添加方法DoSomeMagic(),使用默认实现或抽象。 派生类应该覆盖它来做它的魔力。
这样的事情可能是:
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;
}
虚拟方法将是一个很好的解决方案。 您在基类中创建一个方法ParseMessage
,它处理每个派生类型共有的所有内容,然后覆盖特定设备。
为了仍然能够处理其他消息类型,您需要根据需要调用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;
}
}
}
如果您的基类没有处理任何其他消息,则代码可能更简单(并使用abstract
)。 但是,在这种情况下,我会考虑将Web套接字代码移动到派生类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.