我已经阅读了几个类似的问题,但似乎没有解决我面临的问题.典型的答案是转换为派生类,但我不能,因为我不知道派生类类型.
这是我的例子:
- class WireLessDevice { // base class
- void websocket.parsemessage(); // inserts data into the wireless device object
- }
- class WiFi : WireLessDevice { // derived class
- GPSLoc Loc;
- }
无线设备也可以被导出来制造蓝牙,Wi-Max,Cellular等设备,因此我不知道哪种类型的无线设备将接收数据.
当在基类中的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;
- }