接口 - 定义多种类型的行为
接口包含非抽象 class 或 struct 必须实现的一组相关功能的定义。 接口可以定义 static 方法,此类方法必须具有实现。 接口可为成员定义默认实现。 接口不能声明实例数据,如字段、自动实现的属性或类似属性的事件。 C#不支持类的多重继承,使用接口可以在类中包括来自多个源的行为。 如果要模拟结构的继承,也必须使用接口,因为它们无法实际从另一个结构或类继承。
interface IEquatable< T>
{
bool Equals ( T obj) ;
}
public class Car : IEquatable< Car>
{
public string ? Make { get ; set ; }
public string ? Model { get ; set ; }
public string ? Year { get ; set ; }
public bool Equals ( Car? car)
{
return ( this . Make, this . Model, this . Year) ==
( car?. Make, car?. Model, car?. Year) ;
}
}
类的属性和索引器可以为接口中定义的属性或索引器定义额外的访问器。
public interface IExample
{
int ReadOnlyProperty { get ; }
string ReadWriteProperty { get ; set ; }
int this [ int index] { get ; set ; }
}
using System ;
public interface IBaseInterface
{
void BaseMethod ( ) ;
}
public interface IDerivedInterface : IBaseInterface
{
void DerivedMethod ( ) ;
}
public class MyClass : IDerivedInterface
{
public void BaseMethod ( )
{
Console. WriteLine ( "MyClass: Implementing BaseMethod from IBaseInterface." ) ;
}
public void DerivedMethod ( )
{
Console. WriteLine ( "MyClass: Implementing DerivedMethod from IDerivedInterface." ) ;
}
}
public class Program
{
public static void Main ( )
{
MyClass myClass = new MyClass ( ) ;
IDerivedInterface derivedInterface = myClass;
derivedInterface. BaseMethod ( ) ;
derivedInterface. DerivedMethod ( ) ;
IBaseInterface baseInterface = myClass;
baseInterface. BaseMethod ( ) ;
DerivedClass derivedClass = new DerivedClass ( ) ;
derivedClass. BaseMethod ( ) ;
IBaseInterface baseInterfaceFromDerived = derivedClass;
baseInterfaceFromDerived. BaseMethod ( ) ;
IDerivedInterface derivedInterfaceFromDerived = derivedClass;
derivedInterfaceFromDerived. DerivedMethod ( ) ;
IDefaultInterface defaultInterface = new DefaultImplementationClass ( ) ;
defaultInterface. DefaultMethod ( ) ;
}
}
public class DerivedClass : MyClass , IBaseInterface
{
public new void BaseMethod ( )
{
Console. WriteLine ( "DerivedClass: Overriding BaseMethod." ) ;
}
}
public interface IDefaultInterface
{
void DefaultMethod ( )
{
Console. WriteLine ( "IDefaultInterface: Default implementation of DefaultMethod." ) ;
}
}
public class DefaultImplementationClass : IDefaultInterface
{
}