首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

真心求知道协变逆变怎么体现出代码重用

2012-04-27 
真心求知道协变逆变如何体现出代码重用?C# code//动物类public abstract class Animal{public string str

真心求知道协变逆变如何体现出代码重用?

C# code
//动物类public abstract class Animal    {        public string str = "Animal";        public void animal()        {        }        public void dog()        {        }    }//继承动物的狗public class Dog : Animal    {        public string str = "Dog";        public void animal()        {        }        public void dog()        {        }    }//使用协变和逆变static void Main(string[] args)        {            Dog dog = new Dog();            Animal animal = dog;            List<Dog> dogs = new List<Dog>();            dogs.Add(dog);            //下面进行协变:依然会调用自身的方法。这个协变到底有什么作用?直接new Animal本身,直接用他的不就可以了么?干嘛还要这么麻烦呢?            IEnumerable<Dog> someDogs = dogs;            IEnumerable<Animal> someAnimals = someDogs;            someAnimals.ToList()[0].animal();            someDogs.ToList()[0].animal();            //public delegate void Action<in T>(T obj);            //下面进行逆变,同理,为什么这样的动作不在模型类直接在动物类添加“叫”,非要在这里+个方法,然后让狗调用这么麻烦呢?            Dog aDog = new Dog();            Action<Animal> actionAnimal = new Action<Animal>(a => { Console.Write("叫"); Console.Read(); });            Action<Dog> actionDog = actionAnimal;            actionDog(aDog);                     }


[解决办法]
楼主先把继承搞明白再研究这些东西吧。
你看看你自己写的Animal和Dog,除了Dog继承了Animal之外一点点关系都没有。

热点排行