Generic Class Covariance

后端 未结 3 730
独厮守ぢ
独厮守ぢ 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:51

    Looks like .NET Framework 4.0 supports covariance in generic interfaces and delegates. So, I happened to compile the code by adding a generic interface.

    public interface IInterface
    {
        ...
    }
    
    public class Class1 : IInterface
    {
        ...
    }
    
    public interface IBase where T: IInterface
    {
        // Need to add out keyword for covariance.
    }
    
    public class Base : IBase where T : IInterface
    {
        ...
    }
    
    public class Class2 : Base where T : IInterface
    {
        ...
    }
    
    .
    .
    .
    
    public SomeMethod()
    {
        List> list = new List>();
        Class2 item = new Class2();
        list.Add(item); // No compile time error here.
    }
    

提交回复
热议问题