如何限制类不要在C#中实现Interface的所有方法?

use*_*645 5 c# interface

某处我读过这个问题.我们怎样才能处理这样的情况:

我有一个接口,在我有四种方法:Add,Subtract,Multiply,Divide.

我有两个AB类.

我希望AB实现此接口.但我想要这样的情况:

  • A只能访问Add,Subtract.
  • B只能访问Multiply,Divide.

请告诉我这在C#中是如何实现的?或者通过一些技巧,如果可能的话请告诉我.

dem*_*key 6

接口的要点是定义两个对象之间的契约.如果你说你的对象只想实现一些契约,那么这就破坏了界面的含义.

为什么不使用多个接口,一个用于Add/Subtract,另一个用于Multiply/Divide.您的类可以实现这些接口中的任何一个或两个.


Guf*_*ffa 1

You can't avoid implementing all methods of the interface. If you inherit the interface you have to fulfil it.

In some situations some methods of an interface can't have a useful implementation for a specific class. After you have come to the conclusion that you should implement the interface despite this, there are some things that you can do:

  • You can implement a method as doing nothing. If the class already does what's expected without it, you can just accept the method call and silently do nothing.

  • You can throw a NotSupportedException, if some result is expected by calling the method, that the class can't fulfil. Naturally this should only be done if the method is not crucial for how the interface is supposed to be used.


Also, you have the choise of implementing interface members implicitly or explicilty. Implicitly is the normal way, where the member is visible both when the type of the reference is the interface and when it's the class.

To implement a member explicitly makes it only visible when the type of the reference is the interface, not when it's the class.

If the Multiply method is implemented explicitly in the class A (and the interface is named ICanCalc):

A obja = new A();
ICanCalc infa = new A();

infa.Multiply(); // works fine
obja.Multiply(); // gives a compiler error
Run Code Online (Sandbox Code Playgroud)

However, the method is only hidden, you can still use it by simply casting the reference:

(ICanCalc)obja.Multiply(); // works fine
Run Code Online (Sandbox Code Playgroud)