使用通用方法將介面作為約束型別
這是一個如何在類 Animal 上使用通用型別 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);
//Output: Grass was eaten by: Herbivore
lion.Eat(sheep);
//Output: Herbivore was eaten by: Carnivore
在這種情況下,如果你嘗試呼叫:
sheep.Eat(lion);
這是不可能的,因為物件獅子沒有實現介面 IFood。嘗試進行上述呼叫將生成編譯器錯誤:“型別’食肉動物’不能在泛型型別或方法’Animal.Eat(TFood)
‘中用作型別引數’TFood’。沒有隱式引用轉換’ Carnivore’到’IFood’。“