开发者

Determine if a Class implements an Interface without referencing it

开发者 https://www.devze.com 2023-01-13 23:05 出处:网络
I feel like this should be very possible. I have an interface, let\'s call it IJerry. Now, I have a class in variable x. That class implements IJerry perfectly. The thing is, that class does not ever

I feel like this should be very possible.

I have an interface, let's call it IJerry. Now, I have a class in variable x. That class implements IJerry perfectly. The thing is, that class does not ever reference IJerry. It just happens to have a perfect, compliant signature with IJerry.

Make sense? Let's say you create a class called MyClass that implements INotifyPropertyChanged. Then you delete the MyClass : INotifyPropertyChanged declaration from the class but you LEAVE the implementation inside the class.

Is there a way to determine if the class开发者_StackOverflow社区 "implements" an interface even if it does not make an explicit reference to it?


Not easily.

You would have to read the fields, method, and properties of the interface using reflection, and then check if the class has them (again using reflection)

Alternately, if you are using C#4, you could just forget about IJerry, and put MyClass in a dynamic variable, and then you C# figure out at run-time for it has the methods being called.


There's a lot more to implementing an interface than meets the eye. For one, implementation methods are virtual, even though you don't use that keyword. In fact, you're not allowed to use that keyword. For another, the compiler rearranges the methods to match the method table layout of the interface. Removing the inherited interface from the declaration is guaranteed to make the result incompatible. The methods won't be virtual anymore.

What you are pursuing is called 'dynamic dispatch'. Implemented in the DLR and integrated into .NET 4.0 and the C# 4.0 language. Re-inventing the System.Reflection code and making it efficient is a major undertaking.


You would have to use reflection to see if x had methods that matched the ones on IJerry. The real question is, what are you going to do with the answer? Prior to version 4, C# doesn't support "duck typing", so in order to use your class where an IJerry is required you have to write adapter code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号