.net 4 generics question

I have the following class structure:

public class A : AInterface { }
public interface AInterface { }

public class B<T> : BInterface<T> where T : AInterface 
{
    public T Element { get; set; }
}
public interface BInterface<T> where T : AInterface 
{
    T Element { get; set; }
}

public class Y : B<A> { }

public class Z<T> where T : BInterface<AInterface> {}

public class Test
{
    public Test()
    {
        Z<Y> z = new Z<Y>();
    }
}

This gives me the following erorr compiler in C # 4.0. The type "Test.Y" cannot be used as a parameter of type "T" in the generic type or method "Test.Z". There is no implicit conversion of links from "Test.Y" to "Test.BInterface".

Am I though covariance in generics should do this job? Any help would be appreciated.

+3
source share
2 answers

, , , . , "out" :

public interface BInterface<out T> where T : AInterface { } 

MSDN: (# Visual Basic).

+4

, out. :

public interface BInterface<out T> where T : AInterface { }
public class Z<out T> where T : BInterface<AInterface> {}

, .

+1

Source: https://habr.com/ru/post/1726765/


All Articles