I read all about covariance, contravariance and invariance, but I still don't understand how to develop code

I searched and read / studied as much as seemed reasonable before posting this. I found similar questions, but most of the messages are actually more about passing a List of Derived Types to function calls that require a Base Type List. I can appreciate animal examples and feel that I have a much better understanding after my research.

Saying, I still cannot figure out how to solve in my particular use case. I need to collect instances of "GenericClass of TestInterface (s)" in the collection. I copied / pasted under my best efforts what might seem like the best way to accomplish tasks.

namespace Covariance
{
    class Program
    {

        protected static ISet<GenericClass<TestInterface>> set = new HashSet<GenericClass<TestInterface>>();

        static void Main(string[] args)
        {
            set.Add(new GenericClass<A>());
            set.Add(new GenericClass<B>());
        }
    }

    class GenericClass<TemplateClass> where TemplateClass : TestInterface
    {
        TemplateClass goo;
    }

    public interface TestInterface
    {
        void test();
    }
    public class A : TestInterface
    {
        public void test()
        {
        }
    }

    class B : A
    {
    }
}

:

error CS1503: 1: 'Covariance.GenericClass' 'Covariance.GenericClass'

error CS1503: 1: 'Covariance.GenericClass' 'Covariance.GenericClass'

/ . , , . !

+4
1

(in, out) , . , GenericClass, :

interface IGenericClass<out TemplateClass> where TemplateClass : TestInterface {
    TemplateClass goo { get; }
}
class GenericClass<TemplateClass> : IGenericClass<TemplateClass> where TemplateClass : TestInterface
{
    public TemplateClass goo { get; }
}

class Program {
    protected static ISet<IGenericClass<TestInterface>> set = new HashSet<IGenericClass<TestInterface>>();

    static void Main(string[] args) {
        set.Add(new GenericClass<A>());
        set.Add(new GenericClass<B>());
    }
}
+3

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


All Articles