在C#中,一个类可以继承另一个类和一个接口吗? [英] In C#, can a class inherit from another class and an interface?

查看:35
本文介绍了在C#中,一个类可以继承另一个类和一个接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一个类是否可以继承一个类和一个接口.下面的示例代码不起作用,但我认为它传达了我想要做的事情.我想这样做的原因是因为在我的公司,我们制造 USB、串行、以太网等设备.我正在尝试开发一个通用组件/接口,我可以用它来为我们所有的设备编写程序,这将有助于保持我们所有应用程序的常见事情(如连接、断开连接、获取固件)相同.

I want to know if a class can inherit from a class and an interface. The example code below doesn't work but I think it conveys what I want to do. The reason that I want to do this is because at my company we make USB, serial, Ethernet, etc device. I am trying to develop a generic component/interface that I can use to write programs for all our devices that will help keep the common things (like connecting, disconnecting, getting firmware) the same for all of our applications.

补充一下这个问题:如果 GenericDevice 在不同的项目中,我可以将 IOurDevices 接口放在那个项目中,然后如果我添加对第一个项目的引用,然后让 USBDevice 类实现该接口吗?因为只想引用一个项目,然后根据设备的不同实现不同的接口.

To add to this question: If GenericDevice is in different project, can I put the IOurDevices interface in that project then then make the USBDevice class implement the interface if I add a reference to the first project? Because would like to just reference one project and then implement different interfaces depending on what the device is.

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;
   }
}

推荐答案

是的.试试:

class USBDevice : GenericDevice, IOurDevice

注意:基类应该在接口名称列表之前.

Note: The base class should come before the list of interface names.

当然,您仍然需要实现接口定义的所有成员.但是,如果基类包含与接口成员匹配的成员,则基类成员可以作为接口成员的实现,您无需再次手动实现.

Of course, you'll still need to implement all the members that the interfaces define. However, if the base class contains a member that matches an interface member, the base class member can work as the implementation of the interface member and you are not required to manually implement it again.

这篇关于在C#中,一个类可以继承另一个类和一个接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆