当前位置:  开发笔记 > 编程语言 > 正文

在C#中的接口实现中使用继承的接口

如何解决《在C#中的接口实现中使用继承的接口》经验,为你挑选了1个好方法。

如何实现获取继承接口的函数?我有这些接口:

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)"?还是只是方便?)



1> Daan..:

这是解决方案.您应该使用泛型约束.

        interface IShelter where 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();
        }
    }

推荐阅读
wurtjq
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有