【发布时间】:2010-02-19 15:56:13
【问题描述】:
我不确定我想做的事情是否违反了面向对象的准则,所以我会解释我在做什么,如果我错了,希望你们能告诉我一个更好的方法。我之前尝试过问这个问题,但我举了一个糟糕的例子,所以我认为它只会造成更多的混乱。
所以我有一个主类,USBCommunicator。构造函数采用您要与之交谈的设备类型的产品 ID。 USBCommunicator 类还有一个属性,用于与特定的序列号进行通信。 USBCommunicator 具有 OpenConnection 和 CloseConnection 方法,它们将打开或关闭数据流以在 USB 设备和 PC 之间传输数据。
为了通过流发送数据,我希望 USBCommunicator 能够创建一个 Report 类的实例,设置一些参数,例如超时、ReportID 等,然后调用 Report 类的 Send() 方法来实际发送数据。我认为除了 USBCommunicator 之外的任何类都不能创建 Report 类的实例。 (例如,Boat 女士不应该能够创建 CarDoor 类的实例,因为船不能有车门。)最后,我最初认为 Report 类应该能够访问 USBCommunicator 的成员但我想这不是真的。如果 USBCommunicator 打开设备的流,所有 Report 真正需要的是传入的参数,它是对打开流的引用/句柄。但是该流应该是什么形式才能允许它被高级应用程序传递?公共财产?这似乎不太对。
这就是我目前所拥有的......
namespace USBTools
{
class HighLevelApplication
{
void main()
{
USBCommunicator myUSB = new USBCommunicator("15B3");
myUSB.SerialNumber = "123ABC";
myUSB.OpenConnection();
myUSB.Report ReportToSend = new myUSB.Report(//how do I pass the stream here?);
//It would be nice if I didn't have to pass in the stream because the stream shouldn't
//be publicly available to the HighLevelApplication class right?
ReportToSend.ReportID = 3;
ReportToSend.Timeout = 1000;
ReportToSend.Data = "Send this Data";
ReportToSend.Send();
}
}
class myUSB
{
myUSB(string PID)
{
//...
}
// public SerialNumber property
// private stream field ???
// public OpenConnection and CloseConnection methods
class Report
{
Report(stream StreamToUse)
{
//...
}
Send()
{
//send the data
}
}
}
}
【问题讨论】:
标签: c# class inheritance oop