学习C#,有一个随机的问题,我似乎搞不懂。我见过声明接口类型变量的代码。例如: ISomeInterface someInterface = ..。而不是ClassImplementingInterface someObject = ..。
1)为什么要声明变量为接口类型,而不是实现它的实际对象?
( 2)有利有弊.这个练习是否附加了一个名字,这样我就可以在上面读更多?
发布于 2020-05-11 22:34:28
我们何时可以这样做的一个实际例子是,当我们希望对象在创建后在特定接口的约束范围内运行时。考虑以下代码:
public static void Main()
{
IReadableFruit fruit = new Apple("big");
fruit.FruitSize = "small"; // this does not work!
fruit.EatFruit(); // nor does this!
Apple apple = new Apple("big");
apple.FruitSize = "small"; // this does!
apple.EatFruit(); //and so does this.
}
public interface IReadableFruit
{
string FruitSize { get; }
}
public interface IEdibleFruit
{
void EatFruit();
}
public class Apple : IReadableFruit, IEdibleFruit
{
public string FruitSize { get; set; }
public Apple(string fruitSize)
{
FruitSize = fruitSize;
}
public void EatFruit()
{
Console.WriteLine("om nom nom");
}
}在第一个实例化中,我们使用接口,它将属性定义为可读但不一定是可写的;一旦实例化了结果,它现在只在IReadableFruit接口描述的界限内运行,即使实际的类继承自其他接口,或者在实现中具有其他可用的属性或方法。
正如@Anzurio在他的评论中提到的,这是多态性的一个例子。
https://stackoverflow.com/questions/61740236
复制相似问题