【发布时间】:2011-04-29 04:33:28
【问题描述】:
我是一名主要使用嵌入式设备(使用 C 和汇编进行编程)的开发人员。我的 C# 和 OOP 知识非常有限(尽管我可以在必要时假装通过它)。我有五个通过 USB 与 PC 连接的设备。 PC 进行一些计算并将结果发送到设备。对每个设备执行相同的计算,但计算方式不同。对于每台设备,我都有一个 C# Windows 窗体应用程序,该应用程序执行一些工作并将数据来回发送到设备。目前,我正在尝试将五个不同的应用程序合并为一个,以便我们可以轻松地进行更改、轻松地添加新设备并拥有标准的用户界面。我的问题是我不完全知道最好的方法,因为直到运行时我才知道将使用哪个设备。我试图避免一堆 if 语句,我希望能够将每个设备放在一个单独的文件中。这是我正在谈论的一些伪代码。
class Device //This is what EVERY device can do
{
...
DoWork1();
DoWork2();
DoWork3();
...
}
class Device1
{
...
DoWork1(); //This is how the work is done for this device
DoWork2();
DoWork3();
...
}
class Device2
{
...
DoWork1(); //This is how the work is done for this device (not the same way as Device1)
DoWork2();
DoWork3();
}
public partial class frmMain : Form
{
private (some kind of object or something) CurrentDevice;
public frmMain()
{
...
//Determine what device (could be one of five) is currently being used
CurrentDevice = (which device is currently being used)
//Could be CurrentDevice = new Device1();
}
}
private void Button1_Click()
{
CurrentDevice.DoWork1(); //But this could be Device1.DoWork1() or Device2.DoWork1(), depending on what device is currently being used (which was determined in the frmMain constructor)
}
我不太确定,但我想我可以使用接口或者继承 Device1 类的 Device 类并覆盖这些方法...但我不知道如何使用一种通用方式说 CurrentDevice.DoWork1() 因为 CurrentDevice 可能是 Device1 或 Device2。
任何想法将不胜感激。我在 Windows XP SP3 和 Windows 7 上使用带有 .NET 3.5 的 Visual Studio 2008。
我希望我对问题的描述足够好。如果没有,或者我没有提到我应该提到的东西,请告诉我。我是 stackoverflow 和 C# 的新手。
谢谢,
迈克尔
【问题讨论】:
-
感谢大家的帮助和建议。我决定使用 Sisyphus 提供的解决方案,因为它非常适合我当前的应用程序。不过,每个人都对此提出了很好的意见,我感谢大家。 :)