问题描述
我已经读过一些类似的问题,但是似乎都无法解决我面临的问题。典型的答案是将其强制转换为派生类,但由于我不知道派生类的类型而无法这样做。
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.
这里是我的示例:
class WireLessDevice { // base class
void websocket.parsemessage(); // inserts data into the wireless device object
}
class WiFi : WireLessDevice { // derived class
GPSLoc Loc;
}
也可以衍生出无线设备来制造蓝牙,Wi-Max,蜂窝,等设备,因此我不知道哪种类型的无线设备将接收数据。
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.
在基类中的websocket上收到GPS数据包时,我需要更新了派生设备的位置。
When a GPS packet is received on the websocket in the base class I need to update the derived device's location.
我以为可能是通过队列发送消息或创建事件处理程序并在事件参数中发送位置,但是当这些参数出现时显得有些笨拙
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?
推荐答案
正确的方法是在基类,默认实现或抽象的
中添加方法DoSomeMagic()。
派生类应该重写它以发挥其魔力。
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.
类似这样的东西:
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;
}
这篇关于如何从基类调用派生类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!