Interface functionality&Importance接口的功能和重要性

Interface is a new great type in CLR.
    it's hard to represent just with words. we can describe the importance of interface using a sample as following shown.
在CLR中,interface 是一个非常重要的新的类型(C++中没有interface,不过有abstract class :) 嘿嘿)
很难用文字说明,我给出一个例子,你就会清楚了 :)

case 1: a sample without interface
第一种情况:不用interface
public sealed class ChinesePerson{...}
public sealed class AmericanPerson{...}
public sealed class Turnip{...}[turnip:萝卜,就是乱七八糟的东西了]

class Doctor
{
    void OperateAndTransfuseBlood(object patient)
    //what if patient is a turnip? unable to verify!
    {
    }
}
    in this sample,the Doctor.OperatonAndTransfuseBlood method accepts a single parameter of type system.object. the type system.object is the universal type in the CLR; this means that one canpass instances of any type as the parameter value, such as ChinesePerson instance, or AmericanPerson instance, even a turnip instance. this logical error will not be discovered until runtime.
    在这个例子中,医生的验血method需要一个病人作为参数,而因为有2种类型的病人(中国人和美国人),为了能够接受这两种类型的任何一种,采取了其共同的基类object作为参数类型。这样产生的问题是可能一个萝卜也可以作为其参数的,(sounds ridiculous) 这个错误在compile-time是无法检查出来的,直到run-time.
case2 :a sample with interface to solve this problem.
    public interface IPatient{...}
    public sealed class ChinesePerson:IPatient {...}
    public sealed class AmericanPerson:IPatient {...}    
    public sealed class Turnip {...}
    public class Doctor
    {    
        void OperationAndTranfuseBlood(IPatient patient)
    {
    
    in this example, there is a category of types called IPatient, That category is declared as an Interface. Types that are compatible with IPatient explicitly declare this compability as part of their type definition. Both ChinesePerson and AmericanPerson do exactly this. The Operat..Blood method now declares its parameter to disallow types that are not comptible with IPatient. Cos the Turnip type did not declare compatibility with IPatient ,attempts to pass turnip objects to this method will fail at compile time. This solutionis preferable to simply providing two explicit overloads of the method-one for ChinesePerson and one for AmeracanPerson--cos this approach lets one define new types that one can pass to the Doctor.Operateand..Blood method without having to explicitly define new overloads.
        在这个例子中,我们定义了一种接口类型IPatient。所有与之兼容的类型都被显式定义,即被继承的类ChinesePerson和AmercanPerson.这样在Doctor.Oper..Blood中,我采用IPatient作为参数类型,这样所有与IPatient兼容的参数才能被传入,因为ChinesePerson和AmercanPerson都继承于IPatient,所以都能满足条件,而萝卜Turnip与IPatient是毫无关系的。若将萝卜作为其参数,在compile-time将会被检查出。从而省去了需要overload Operatio..Blood 这个method

so cool ! :)
原文地址:https://www.cnblogs.com/Winston/p/1169675.html