你需要转换为接口的最好原因是,如果你正在编写针对对象的代码,而你不知道它们具体的类型,也不想知道。如果你知道可能会遇到实现特定接口的对象,那么你可以从对象中获取值,而不必知道该对象的具体类。此外,如果你知道一个对象实现了给定的接口,那么该接口可能定义了你可以执行的方法,以对该对象执行某些操作。
以下是一个简单的例子:
public interface IText
{
string Text { get; }
}
public interface ISuperDooper
{
string WhyAmISuperDooper { get; }
}
public class Control
{
public int ID { get; set; }
}
public class TextControl : Control, IText
{
public string Text { get; set; }
}
public class AnotherTextControl : Control, IText
{
public string Text { get; set; }
}
public class SuperDooperControl : Control, ISuperDooper
{
public string WhyAmISuperDooper { get; set; }
}
public class TestProgram
{
static void Main(string[] args)
{
List<Control> controls = new List<Control>
{
new TextControl
{
ID = 1,
Text = "I'm a text control"
},
new AnotherTextControl
{
ID = 2,
Text = "I'm another text control"
},
new SuperDooperControl
{
ID = 3,
WhyAmISuperDooper = "Just Because"
}
};
DoSomething(controls);
}
static void DoSomething(List<Control> controls)
{
foreach(Control control in controls)
{
Console.WriteLine("ID: {0}", control.ID);
if (control is IText)
Console.WriteLine("Text: {0}", ((IText)control).Text);
if (control is ISuperDooper)
Console.WriteLine("Text: {0}",
((ISuperDooper)control).WhyAmISuperDooper);
}
}
}
运行这个小程序会输出以下结果:
ID:1
文本:我是一个文本控件
ID:2
文本:我是另一个文本控件
ID:3
文本:只是因为
请注意,我不需要在DoSomething方法中编写任何代码,也不需要知道所有工作对象都是具体对象类型。我唯一知道的是,我正在处理至少是Control类实例的对象。然后,我可以使用接口查找它们可能具有的其他内容。
对于对象使用接口的原因有很多,但它为您提供了一种松散的访问对象的方式,而无需确切知道对象是什么。
想象一下世界上所有的信用卡,每个公司都有自己的信用卡,接口却是相同的,因此每个读卡器都可以刷过遵循标准的信用卡。与使用接口类似。