Interfaces enable you to separate the definition of objects from
their implementation
在这种情况下,对象的定义是指对象的公开部分。
在下面的示例中,它引用公共属性Name / Age 和公共方法Insert 和Update。
在下面的类中,Person 的定义及其实现(用于实现属性和方法的代码)是相同的,即类 Person。
Class Person
{
private string _name; //private fields
private string _age; //private fields
public Name {get {....} set {.....}} //public properties
public Age {get {....} set {.....}} //public properties
public void Insert() {.......} //public methods
public void Update() {.......} //public methods
}
注意:“........”表示调用这些属性/方法时将调用的实际代码,即它们的实现。
现在,如果我要为此创建一个名为
的接口
Interface IPerson
{
public Name get; set; //public properties
public Age get; set; //public properties
public void Insert(); //public methods
public void Update(); //public methods
}
然后做Class Person : IPerson
那么我所做的是我现在将定义(即IPerson)与实现(即Person)分开。
注意:为什么这是有用的已经被 Aamir 和 Gravell 在他们上面的回答中介绍过,所以我不会重复同样的内容