如何实现获取继承接口的函数?我有这些接口:
interface IAnimal interface IDog : IAnimal interface ICat : IAnimal interface IShelter class DogShelter : IShelter class CatShelter : IShelter
现在我希望IShelter有一个功能:
Store(IAnimal animal)
但是我希望DogShelter像这样实现它:
Store(IDog animal)
和CatShelter这样:
Store(ICat animal).
有没有办法做到这一点?除了DogShelter实施Store(IAnmial动物)并检查"if(animal is IDog)"之外?
我应该使用Store(IAnimal animal)然后用(IDog)动物施放它吗?
(我想使用关于IDog和ICat的接口继承.在实际代码中不能进行类继承)(计算时间在这一点上是很重要的.使用Store(IDog动物)而不是检查"if"是否更便宜?动物是IDog)"?还是只是方便?)
这是解决方案.您应该使用泛型约束.
interface IShelterwhere T : IAnimal { void Store(T animal); } class DogShelter : IShelter { public void Store(IDog animal) { throw new NotImplementedException(); } } class CatShelter : IShelter { public void Store(ICat animal) { throw new NotImplementedException(); } }