Determine if a class implements an interface without reference to it

I feel that this should be very possible.

I have an interface, let me call it IJerry. Now I have a class in the variable x. This class implements IJerry perfectly. The fact is that this class never refers to IJerry. I just have a perfect, compatible signature with IJerry.

Make sense? Let's say you create a class MyClass that implements INotifyPropertyChanged. Then you remove the declaration "MyClass: INotifyPropertyChanged" from the class, but you execute the implementation inside the class.

Is there a way to determine if a class implements an "interface" even if it does not explicitly reference it?

+3
source share
3 answers

Not easy.

, , , ( )

, # 4, IJerry MyClass , # , .

+7

, . -, , . . , . . .

, , " ". DLR .NET 4.0 # 4.0. System.Reflection .

+2

You would need to use reflection to see if x has methods that match those on IJerry. The real question is: what are you going to do with the answer? Prior to version 4, C # does not support duck printing, so to use your class where IJerry is required, you need to write the adapter code.

+1
source

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


All Articles