这是有关如何在动物类的Eat方法中使用通用类型TFood的示例
public interface IFood { void EatenBy(Animal animal); } public class Grass: IFood { public void EatenBy(Animal animal) { Console.WriteLine("Grass was eaten by: {0}", animal.Name); } } public class Animal { public string Name { get; set; } public void Eat<TFood>(TFood food) where TFood : IFood { food.EatenBy(this); } } public class Carnivore : Animal { public Carnivore() { Name = "Carnivore"; } } public class Herbivore : Animal, IFood { public Herbivore() { Name = "Herbivore"; } public void EatenBy(Animal animal) { Console.WriteLine("Herbivore was eaten by: {0}", animal.Name); } }
您可以这样调用Eat方法:
var grass = new Grass(); var sheep = new Herbivore(); var lion = new Carnivore(); sheep.Eat(grass); //产出:草食者:草食动物 lion.Eat(sheep); //产出:食草动物被食肉动物食用
在这种情况下,如果您尝试致电:
sheep.Eat(lion);
这将是不可能的,因为对象狮子没有实现IFood接口。尝试进行上述调用将生成编译器错误:“类型'Carnivore'不能用作通用类型或方法' '中的类型参数'TFood '。没有从'Carnivore'到'IFood'的隐式引用转换。 。”Animal.Eat(TFood)