IDictionary<,> contravariance?

前端 未结 6 727
不思量自难忘°
不思量自难忘° 2020-12-06 04:58

I have the following method in an external class

public static void DoStuffWithAnimals(IDictionary animals)

In my cal

6条回答
  •  -上瘾入骨i
    2020-12-06 05:41

    You could modify public static void DoStuffWithAnimals(IDictionary animals) to add a generic constraint. Here is something that works for me in LINQPad:

    void Main()
    {
        var lions = new Dictionary();
        lions.Add("one", new Lion{Name="Ben"});
        AnimalManipulator.DoStuffWithAnimals(lions);
    }
    
    public class AnimalManipulator
    {
        public static void DoStuffWithAnimals(IDictionary animals)
        where T : Animal
        {
            foreach (var kvp in animals)
            {
                kvp.Value.MakeNoise();
            }
        }
    }
    
    public class Animal
    {
        public string Name {get;set;}
        public virtual string MakeNoise()
        {
            return "?";
        }
    }
    
    public class Lion : Animal
    {
        public override string MakeNoise()
        {
            return "Roar";
        }
    }
    

提交回复
热议问题