IDictionary<,> contravariance?

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

I have the following method in an external class

public static void DoStuffWithAnimals(IDictionary animals)

In my cal

6条回答
  •  借酒劲吻你
    2020-12-06 05:34

    Solution wise you could do something like this, just pass in an accessor instead:

        public static void DoStuffWithAnimals(Func getAnimal)
        {
        }
    
        var dicLions = new Dictionary();
        DoStuffWithAnimals(s => dicLions[s]);
    

    Obviously that is likely to be a bit simple for your needs, but if you only need a couple of the dictionary methods it's pretty easy to get that in place.

    This is another way that gives you a bit of code re-use between your animals:

        public class Accessor : IAnimalAccessor where T : Animal
        {
            private readonly Dictionary _dict;
    
            public Accessor(Dictionary dict)
            {
                _dict = dict;
            }
    
            public Animal GetItem(String key)
            {
                return _dict[key];
            }
        }
    
        public interface IAnimalAccessor
        {
            Animal GetItem(string key);
        }
    
        public static void DoStuffWithAnimals(IAnimalAccessor getAnimal)
        {
        }
    
        var dicLions = new Dictionary();
        var accessor = new Accessor(dicLions);
        DoStuffWithAnimals(accessor);
    

提交回复
热议问题