No general argument assigned

I am using C # .NET 3.5. I get

The argument type "GenericTest.BarkStrategy" is not assigned to the parameter type "GenericsTest.IAnimalStrategy"

with the following (for this maximally simplified question) code:

using System.Collections.Generic;

namespace GenericsTest {
    class Program {
        static void Main(string[] args) {
            List<IAnimalStrategy<IAnimal>> strategies = 
                new List<IAnimalStrategy<IAnimal>>();
            strategies.Add(new BarkStrategy());
        }
    }

    interface IAnimal { }
    interface IAnimalStrategy<T> where T : IAnimal { }
    class Dog : IAnimal { }
    class BarkStrategy : IAnimalStrategy<Dog> { }
}
+4
source share
1 answer

You must tell the compiler that your interface is covariant: IAnimalStrategy<out T>

namespace GenericsTest
{
    class Program
    {
        static void Main(string[] args)
        {
            List<IAnimalStrategy<IAnimal>> strategies = new List<IAnimalStrategy<IAnimal>>();
            strategies.Add(new BarkStrategy());
        }
    }

    interface IAnimal { }
    interface IAnimalStrategy<out T> where T : IAnimal { }

    class Dog : IAnimal { }
    class BarkStrategy : IAnimalStrategy<Dog> { }
}

Unfortunately, it is only available in C # 4.0: How is general covariance and contra-variance generated in C # 4.0?

To understand the problem, you can forget the list, this line does not compile:

IAnimalStrategy<IAnimal> s = new BarkStrategy();

The interface IAnimalStrategy<IAnimal>can do things in IAnimal, perhaps set a property of typeIAnimal

interface IAnimalStrategy<T> where T : IAnimal 
{
    T Animal {get; set;}
}

Then you can do something like

IAnimalStrategy<IAnimal> s = new BarkStrategy();
s.Animal = new Cat();

. , # 3.5 .
# 4.0 , , T out

interface IAnimalStrategy<out T> where T : IAnimal 
{
    T Animal {get; set;}
}

,

: T IAnimalStrategy.Animal. "T" .

, : #

+13

All Articles