【发布时间】:2011-01-04 18:57:55
【问题描述】:
我想知道一个类是否可以从一个类和一个接口继承。 下面的示例代码不起作用,但我认为它传达了我想要做的事情。 我想这样做的原因是因为在我公司,我们生产 USB、串口、以太网等设备。我正在尝试开发一个通用组件/接口,我可以用它来为我们所有的设备编写程序,这将有助于我们所有应用程序的通用功能(如连接、断开连接、获取固件)保持一致。
补充这个问题:如果 GenericDevice 在不同的项目中,我可以将 IOurDevices 接口放在该项目中,然后如果我添加对第一个项目的引用,则使 USBDevice 类实现该接口?因为只想引用一个项目,然后根据设备实现不同的接口。
class GenericDevice
{
private string _connectionState;
public connectionState
{
get{return _connectionState; }
set{ _connectionState = value;}
}
}
interface IOurDevices
{
void connectToDevice();
void DisconnectDevice();
void GetFirmwareVersion();
}
class USBDevice : IOurDevices : GenericDevice
{
//here I would define the methods in the interface
//like this...
void connectToDevice()
{
connectionState = "connected";
}
}
//so that in my main program I can do this...
class myProgram
{
main()
{
USBDevice myUSB = new USBDevice();
myUSB.ConnectToDevice;
}
}
【问题讨论】:
-
C# 规范第 10.1.4 节详细描述了如何声明具有多种基类型的类。
-
@Eric Lippert : 请您帮我了解一下这个案例是否正确以及将来是否可用?
标签: c# class inheritance interface components