【问题标题】:Using inherited interfaces in interface implementations in C#在 C# 的接口实现中使用继承的接口
【发布时间】:2016-03-07 07:04:55
【问题描述】:

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

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 animal) 并检查“if(animal is IDog)”吗?

我应该先使用 Store(IAnimal animal),然后使用 (IDog)animal 进行投射吗?

(我想使用 IDog 和 ICat 的接口继承。在真实代码中类继承是不可能的) (此时计算时间有点重要。使用 Store(IDog animal) 而不是检查“if(animal is IDog)”是否更便宜?还是只是为了方便?)

【问题讨论】:

  • 使用IShelter<TAnimal> where TAnimal : IAnimal { void Store(TAnimal); } 可能会更好。
  • 如何使用 IShelter 非常重要。您是否打算收集 IShelter 对象,然后找出一些 IAnimal 去哪个 IShelter?如果是这样,将在某处进行类型检查。问题是它是否发生在商店内部。
  • 当然,Jon Hanna 的建议可以为您提供所需的签名,但是从调用者的角度来看,处理仅在类型参数上有所不同的通用接口的多个实例可能会很困难。
  • 我接受了泛型答案。至少在我的情况下,它按预期工作(即降低我的结构的复杂性)。

标签: c# inheritance interface


【解决方案1】:

这里是解决方案。你应该使用generics constraints

        interface IShelter<T> where T : IAnimal
    {
        void Store(T animal);
    }
    class DogShelter : IShelter<IDog>
    {
        public void Store(IDog animal)
        {
            throw new NotImplementedException();
        }
    }
    class CatShelter : IShelter<ICat>
    {
        public void Store(ICat animal)
        {
            throw new NotImplementedException();
        }
    }

【讨论】:

  • 虽然是一个很好的答案,但您通过将IShelter 设为泛型来重新编写它的定义。 OP 可能只想在应用程序的其他地方使用简单的旧 IShelter 而不是 IShelter&lt;T&gt; 的方法。 (请参阅下面问题的 Mike z 的 cmets)
  • 就像软件开发中的每个解决方案一样,我的解决方案也有一个缺点。普通的旧 IShelter 不能重复使用。运行时检查可能是一种选择,但不应该是首选。如果没有正确完成,编译器不会提供帮助。
  • 谢谢!我喜欢这个解决方案。虽然 Micky 的反对是对的,但在我正在做的项目中这不是问题。
  • 很高兴听到这不是问题 Rian。 +1 大安
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
  • 2016-10-23
  • 2023-03-25
  • 1970-01-01
  • 2020-10-17
相关资源
最近更新 更多