5

我基本上IFoo在 Inherited 类中定义了两次。这会导致一些不可预见的后果吗?

interface IFoo {
   ...
}

interface IBar : IFoo {
   ...
}

class Base : IFoo {
   ...
}

class Derived : Base, IBar {
   ...
}

我想要IBar继承的原因IFoo是我可以按Derived原样工作IFoo而不必强制转换它。

if (Derived is IBar)
   // Do work

如果它不继承,我必须强制转换它。这使得使用更加复杂,并且该类的用户可能不理解这IBar只是IFoo.

if (Derived is IBar)
   Derived as IFoo
   // Do work

这是不好的做法吗?这个问题还有哪些其他解决方案?

4

3 回答 3

5

它不会在代码方面造成任何不可预见的情况。这只是多余的。

至于这段代码:

if (Derived is IBar)
   Derived as IFoo

Derived 这是完全没有必要的,因为IFoo, 鉴于您的声明 - 所以不要那样做!

请注意,即使IBar不派生自IFoo,您仍然不需要Derived as IFoo. 鉴于:

interface IFoo {}

interface IBar {}

class Base : IFoo {}

class Derived : Base, IBar 
{
}

然后编译正常:

var derived = new Derived();

IBar bar = derived; // Fine.
IFoo foo = derived; // Also fine.
于 2013-06-18T09:48:38.663 回答
1

您可以显式定义一个实现,Interface从而区分行为

class Derived : Base, IBar {

    void IBar.Method(){

    }

    void Base.Method() {

    }
}

除此之外,您可以这样做,但它是多余的并且可能会引起混乱。请参阅MSDN

于 2013-06-18T09:49:08.707 回答
1

如果我对您的理解正确,您将拥有一种接口层次结构和一种相互镜像的类层次结构。每个类通过从其基类继承并实现所需的附加成员来实现相应的接口。

这很好,我也是这样做的。我不知道有什么更好的方法来做到这一点——这一个好方法。

我认为 IBar 应该像您的主要建议一样扩展 IFoo ,否则消费者需要投入很多。此外,由于您认为 IBar 是IFoo 的特化,因此也将其作为代码中的特化,因此使其扩展 IFoo。

于 2013-06-18T10:00:10.473 回答