Generic Class Covariance

后端 未结 3 732
独厮守ぢ
独厮守ぢ 2020-12-11 06:09

Is it possible to make the following code compile in C#? I do compile similar in Java.

public interface IInterface
{
    ...
}

public class Class1 : IInterf         


        
3条回答
  •  温柔的废话
    2020-12-11 06:47

    No, that is not legal in C#. C# 4 and above support covariance and contravariance of generic interfaces and generic delegates when they are constructed with reference types. So for example, IEnumerable is covariant, so you could say:

    List giraffes = new List() { ... };
    IEnumerable animals = giraffes;
    

    but not

    List animals = giraffes;
    

    Because a list of animals can have a tiger inserted into it, but a list of giraffes cannot.

    Do a web search on covariance and contravariance in C# and you'll find lots of articles on it.

提交回复
热议问题