2016-11-12 52 views
3

下面是使用泛型協變和逆變在接口

class Program 
    { 
     static void Main(string[] args) 
     { 
      ICovariant<Apple> alCov = new Covariant<Apple>(); 
      ICovariant<Fruite> fCov = alCov; 

      IContravariant<Apple> aContra = new Contravariant<Apple>(); 
      IContravariant<Apple> fContra = new Contravariant<Fruite>(); 

     } 


     public class Fruite 
     { 
      public virtual void Print() 
      { 
       Console.WriteLine("Fruite"); 
      } 
     } 

     public class Apple : Fruite 
     { 
      public override void Print() 
      { 
       Console.WriteLine("Apple"); 
      } 
     } 

     interface IContravariant<in T> 
     { 
      void Method(); 

      // This interface can be implicitly cast to MORE DERIVED (downcasting) 
      // Usually means T is used as argument 
      void Method(T argument); 
     }//interface 

     interface ICovariant<out T> 
     { 
      // This interface can be implicitly cast to LESS DERIVED (upcasting) 
      // Used for readonly collections 
      IEnumerable<T> GetList { get; } 
      // Used when T is used as return type 
      T Method(); 
     }//interface 


     public class Covariant<T> : ICovariant<T> 
     { 
      public IEnumerable<T> GetList 
      { 
       get 
       { 
        throw new NotImplementedException(); 
       } 
      } 

      public T Method() 
      { 
       throw new NotImplementedException(); 
      } 
     } 
     public class Contravariant<T> : IContravariant<T> 
     { 
      public void Method() 
      { 
       Console.Write(typeof(T)); 
      } 

      public void Method(T argument) 
      { 
       Console.Write(argument); 
      } 
     } 

    } 

我明白這些行的代碼,因爲它類似於多態性協方差和逆變的示例,並且我understande它

ICovariant<Apple> alCov = new Covariant<Apple>(); 
ICovariant<Fruite> fCov = alCov; 
背後的好處

但我不明白的是像下面幾行那樣的逆轉的好處

IContravariant<Apple> aContra = new Contravariant<Apple>(); 
IContravariant<Apple> fContra = new Contravariant<Fruite>(); 

所以任何人都可以解釋我如何從中受益。使用

+1

'的IEqualityComparer C =新FruiteComparer(); var d = new HashSet (c);' – PetSerAl

回答

1

so could anyone explain with example of how can I take the benefit of it.

一個例子可能是以下幾點:

IContravariant<Fruite> fContra = new Contravariant<Fruite>(); 
List<IContravariant<Apple>> contravariants= new List<IContravariant<Apple>>(); 
contravariants.Add(fContra); 
contravariants.Add(aContra); 

所以如果你改變IContavariant<in T>接口 到IContavariant<T>你會得到一個編譯時錯誤

一個良好例子可能是方法Linq你可以想到一種方法ES同樣的事情,但不使用IEqualityComparer<T>但同樣algorithme到所有的水果

在這個環節

你可以找到一個完整的例子 Comparing Generic Collections