Explicit interface implementation for COM interfaces in C #

Some time ago, I was working on a large refactoring of an old Win32 program implemented with COM, and there were different parts that were implemented using C # (.NET). During my work on this project, I came across a Microsoft page on COM programming in C #, which recommended that C # classes explicitly implement COM interfaces, rather than implantation. I recently tried to remember why, and I could not. I also could not find the page on MSDN. Can someone tell me why Microsoft can recommend this?

+4
source share
2 answers

Hmm, that makes it a little understandable, COM is pure interface-based programming, and the actual implementation of the interfaces must be hidden. Implementing interface methods explicitly automatically gets you because they cannot be made public.

In fact, doing this is completely pointless, you could (and should) just apply the [ClassInterface(ClassInterfaceType.None)] attribute to the class. This in itself ensures that the implementation will not be shown, only the interfaces implemented by the class are visible. Implementing interface methods is clearly not enough. Because you cannot hide the fact that your class inherits from System.Object. Which provides four public Object methods and places a link to mscorlib.tlb in your type library, a link that a real COM client will never use. This will almost always work, because the likelihood that the compiler that uses your class runs on a computer on which .NET is not installed is quite small. But, nevertheless, it is very important, in fact, this is not required.

Just don't do it. Declare the interfaces that you implement, give them the [InterfaceType(ComInterfaceType.InterfaceIsDual)] attribute so that they can be used both early and late. And hide the actual implementation of them using [ClassInterface(ClassInterfaceType.None)] . Only a reasonable way.

+3
source

This is old, but from here: http://msdn.microsoft.com/en-us/library/aa288461%28v=VS.71%29.aspx they mention the interface implementation explicitly, so you can implement multiple interfaces with the same member names.

It also requires your class user to pass an instance of your class to the appropriate interface.

As to why this is especially important for COM: my first hunch is that COM can call one set of methods, while managed code can call another. However, I guess here.

+1
source

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


All Articles