我是C#的新手.最近我读了一篇文章.建议
"接口的一个实际用途是,当创建一个可以的接口引用时
处理实现该接口的不同类型的对象."
基于我测试的(我不确定我的理解是否正确)
namespace InterfaceExample
{
public interface IRide
{
void Ride();
}
abstract class Animal
{
private string _classification;
public string Classification
{
set { _classification = value;}
get { return _classification;}
}
public Animal(){}
public Animal(string _classification)
{
this._classification = _classification;
}
}
class Elephant:Animal,IRide
{
public Elephant(){}
public Elephant(string _majorClass):base(_majorClass)
{
}
public void Ride()
{
Console.WriteLine("Elephant can ride 34KPM");
}
}
class Horse:Animal,IRide
{
public Horse(){}
public Horse(string _majorClass):base(_majorClass)
{
}
public void Ride()
{
Console.WriteLine("Horse can ride 110 KPH");
}
}
class Test
{
static void Main()
{
Elephant bully = new Elephant("Vertebrata");
Horse lina = new Horse("Vertebrata");
IRide[] riders = {bully,lina};
foreach(IRide rider in riders)
{
rider.Ride();
}
Console.ReadKey(true);
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题:
多重遗产)?
(我希望从有经验的人手中收集信息).
编辑:
我想是编辑为以概念为中心.
关键是,你也可以有一个Bike实现的类IRide,而不继承Animal.您可以将接口视为抽象合同,指定此类的对象可以执行接口中指定的操作.
因为C#不支持多重继承(这是一件好事IMHO)接口是指定其他不相关类型的共享行为或状态的方式.
interface IRideable
{
void Ride();
}
class Elephant : Animal, IRideable{}
class Unicycle: Machine, IRideable{}
Run Code Online (Sandbox Code Playgroud)
以这种方式,假设你有一个模拟马戏团的程序(机器和动物有不同的行为,但有些机器和一些动物可以骑行),你可以创建特定于什么是乘坐东西的抽象功能.
public static void RideThemAll(IEnumerable<IRideable> thingsToRide)
{
foreach(IRideable rideable in thingsToRide)
ridable.Ride();
}
Run Code Online (Sandbox Code Playgroud)