2

我有一个 A、B 和 C 类通用的接口。但是现在我需要添加两个方法,它们只适用于 B 类,不适用于 A 类和 C 类。那么,我是否需要将这两个方法添加到公共接口本身并在 A & C 类中抛出未实现的异常,或者有没有更好的方法来做到这一点?

interface ICommon
{
   Method1;
   Method2;
   Method3;
   Method4;
}

Class A: ICommon
{
   Method1;
   Method2;
}

Class B: ICommon
{
   Method1;
   Method2;
   Method3;
   Method4;
}

Class C: ICommon
{
   Method1;
   Method2;
}

提前致谢

4

3 回答 3

8

如果这些方法对其他类(不仅仅是 B)通用:

让 B 扩展另一个接口

interface ICommon2
{
    Method3;
    Method4;
}

class B : ICommon, ICommon2
{
    Method1;
    Method2;
    Method3;
    Method4;
}

如果这些方法仅特定于 B:

class B : ICommon
{
    Method1;
    Method2;
    Method3;
    Method4;
}
于 2013-05-10T17:16:51.610 回答
1

如果你的接口有方法,你只需实现它们,但你可以偷偷做:

Class A: ICommon
{
   public void Method1() 
   {
   }

   public void Method2() 
   {
   }

   void ICommon.Method3() 
   {
       throw new NotSupportedException();
   }

   void ICommon.Method4() 
   {
       throw new NotSupportedException();
   }
}

这正是数组实现IList接口和隐藏成员的方式,例如Add.

于 2013-05-10T17:32:30.843 回答
0

如果两个类必须实现相同的接口,但其中一个类需要的方法多于接口包含的方法,则这些方法不属于该接口。否则其他类也需要这些方法。

接口描述行为,例如 IDisposable 指示 Dispose() 方法。如果您的 Method3() 和 Method4() 实现了某些行为,则应仅从这两个方法中提取一个接口,并将该接口应用于需要这些方法的类。

于 2013-05-10T17:20:06.227 回答