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>();
所以任何人都可以解釋我如何從中受益。使用
'的IEqualityComparer C =新FruiteComparer(); var d = new HashSet (c);' –
PetSerAl