日期:2014-05-18 浏览次数:20849 次
//动物类 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); }