有人可以解释C#中接口的确切用法吗? [英] Can someone explain the exact use of interfaces in C#?

查看:97
本文介绍了有人可以解释C#中接口的确切用法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释C#中接口的确切用法吗?

Can someone explain the exact use of interfaces in C#?

推荐答案

想象一下创建汽车的工厂的情况。你知道每辆车都有一个引擎,可以启动,所以你有以下几点:

Imagine the the situation of having a factory that creates cars. You know that every vehicle has an engine and can be started, so you have the following:

interface IVehicle
{
   Engine vehicleEngine { get; set; }

   bool StartEngine();
}

现在,工厂制造了一系列其他车辆,例如一辆卡车和普通汽车:

Now, the factory makes an array of other vehicles, so for instance a truck and a normal car:

public Car : IVehicle
{
   // MUST implement vehicleEngine and StartEngine:

   public Engine vehicleEngine { get; set; }

   public bool StartEngine()
   {
       // Cars needs to do xyz to start
   }

   public int MaxNumberOfPassenger { get; set; } // Specific to Car
}

然后:

public Truck : IVehicle
{
   // MUST implement vehicleEngine and StartEngine:

   public Engine vehicleEngine { get; set; }

   public bool StartEngine()
   {
       // Trucks needs to do abc to start
   }

   public int MaximumLoad { get; set; } // Specific to Truck
}

因此,这迫使所有车辆实施特定会员属于车辆类别,但也可以专门与他们自己的独特成员。

This therefore forces all vehicles to implement specific members to fall under the category of a vehicle, but then can also be specialized with their own distinct members.

这篇关于有人可以解释C#中接口的确切用法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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