How can I limit a class to not implement all interface methods in C #?

Somewhere I read this question. How can we deal with this situation:

I have the interface, I have four methods: Add, Subtract, Multiply, Divide.

I have two classes A and Bed and .

I want A and B to implement this interface. But I want a situation like this:

  • A can access only Add, Subtract.
  • B can only access Multiply, Divide.

Please tell me how is this possible in C #? Or some trick, if possible, let me know.

+4
source share
5 answers

You cannot avoid implementing all interface methods. If you inherit an interface, you must execute it.

In some situations, some interface methods may not have a useful implementation for a particular class. Once you conclude that you must implement the interface, despite this, there are some things you can do:

  • You can implement the method as doing nothing. If the class is already doing what is expected without it, you can simply accept the method call and silently do nothing.

  • You can throw NotSupportedExceptionit if some result is expected by calling a method that the class cannot execute. Naturally, this should be done only if the method is not critical for using the interface.


, . , , , .

, , , .

Multiply A ( ICanCalc):

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

infa.Multiply(); // works fine
obja.Multiply(); // gives a compiler error

, , , :

(ICanCalc)obja.Multiply(); // works fine
+1

- . , - , .

, Add/Subtract Multiply/Divide. .

+6

, , . :

, , , .

, :

  • IAdditiveOperators, .
  • IMultiplicativeOperators, .

.

+3

:

, Add Subtract A, , Multiply Divide B. , , , , , .

, A B (, , , )

, , .

+2

: Add Substract IAddSubstract, Multiply Divide IMultiplyDivide. (IOperation), IAddSubstract IMultiplyDivide

+2

Source: https://habr.com/ru/post/1544149/


All Articles