C# 學習筆記(Interface) - 08

Interfaces enable to define behavior characteristics or abilities and apply them to classes, irrespective of the class hierarchy.

Give you the ability to define a set of semantically related method and properties that selected class can implement, regardless of the class hierarchy

Declaring Interfaces

Any class that implement an interface must define each and every memebers of that interface.

All of the interfaces methods are public by definition.

Implementing Interface

Cast an object to one of its implemented interfaces and then call one of these interface member.

IValidation val = (IValidation) ssn;
val.Validate();

Query for Implementation by Using is

expression is type

Query for Implementation by Using as

object = expression as type

Interfaces vs. the Alternatives

Explicit Interface Member Name Qualification

Prevent the Implemented memeber of interfaces from becoming public member of class.

Remove the member's access modifier "public" and qualify the member name with the interface name.

When you wan't to hide a member, you can't use an access modifier.

Avoiding Name Ambiguity

Removing the accessor modifier and prepending the member name with the interface name.

note:

  1. If specify that both interfaces are being implemeted but define only one of methods, the specification will result error;
  2. the client code need to cast to appropriate interface

Interface and inheritance

When you cast an object to an interface, the compiler will traverses the inheritance tree until a class is found that contains the interface in its base list.

Combining Interfaces

Public interface Icombo : IDragDrop, Iserializable

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章