实现多个接口 [英] Implements multiple interfaces

查看:112
本文介绍了实现多个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想了解C#中的多个接口的概念,能否请您提供一个示例来详细说明这一点.
还可以有人告诉我为什么在C#中不能进行多重继承.

Hi
I want to understand the concept of multiple interfaces in C#.Can you please provide an example which elaborates this properly.
Also can somebody tell me why multiple inheritance is not possible in C#.

推荐答案

C#中的接口.

接口是定义signature of the functionality合约.

因此,如果一个类正在实现它与外界的接口,则它它提供了特定的行为.

如果某个类正在实现"Idisposable"接口,则表示该类具有释放非托管资源的功能的示例.
现在,使用此类的外部对象知道它具有可以处理未使用的非托管对象的契约.
  • 单个类可以实现多个接口.
  • 如果一个类实现了一个接口,则它必须提供
    实现所有方法.
Interfaces in C#.

Interface is a contract that defines the signature of the functionality.

So if a class is implementing a interface it says to the outer world, that it provides specific behavior.

Example if a class is implementing ‘Idisposable’ interface that means it has a functionality to release unmanaged resources.
Now external objects using this class know that it has contract by which it can dispose unused unmanaged objects.
  • Single Class can implement multiple interfaces.
  • If a class implements a interface then it has to provide
    implementation to all its methods.


我尝试实现多个接口.这是一个描述用法的小示例

vehicle.cs文件的代码
I tried implementing multiple interfaces. This is a small example which describes the usage

code for vehicle.cs file
namespace MultipleInterface
{
  public interface TwoWheeler  { string vehicleType(); }
  public interface FourWheeler { string vehicleType(); }
   
  public class Vehicle: TwoWheeler, FourWheeler
  {
    public int vehicleNumber { get; set; }
    public string vehicleName { get; set; }

    string TwoWheeler.vehicleType()
    {
      return "2 wheeler type";
    }
    string FourWheeler.vehicleType()
    {
      return "4 wheeler type";
    }
  }
}



在default.aspx.cs文件上使用这些接口的代码



code for using these interfaces on default.aspx.cs file

public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {

  }
  protected void Button1_Click(object sender, EventArgs e)
  {
    Vehicle v = new Vehicle();
    TwoWheeler tv = new Vehicle();   // can only call function declared in TwoWheeler interface
    FourWheeler fv = new Vehicle();  // can only call function declared in FourWheeler interface
    v.vehicleName = "Nano";
    v.vehicleNumber = 123498;
    string output = string.Empty;
    output = "Name: " + v.vehicleName + "<br />Type2:" + tv.vehicleType() + "<br />Type:" + fv.vehicleType();
    Label1.Text = output;
  }
}


default.aspx文件的代码


code for default.aspx file

<p>
    <asp:button id="Button1" runat="server" text="Run..." width="128px" xmlns:asp="#unknown">
        onclick="Button1_Click" />
</asp:button></p>
<asp:label id="Label1" runat="server" text="Label" xmlns:asp="#unknown"></asp:label>



希望对初学者有所帮助.非常感谢.



Hope it will help beginners. Thanks a lot.


这篇关于实现多个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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