Will VB.NET automatically generate ComClass attrib

2019-07-15 11:01发布

I've run across some VB.NET code that explicitly creates three GUID constants and uses them in a class's ComClass attribute. I've written COM-aware classes in the past just by checking the "Make COM-Visible" and "Register for COM interop" options in the project options. Is this explicit code simply unnecessary, or is it doing something above-and-beyond what those two options do? Here's a snippet:

<ComClass(MenuHandler.ClassId, MenuHandler.InterfaceId, MenuHandler.EventsId)> _
Public Class MenuHandler
    Public Const ClassId As String = "A2204623-A902-44d4-B524-FDFFCD176E53"
    Public Const InterfaceId As String = "3449CA8B-16DF-4a61-8BAB-DFF27AE70F5E"
    Public Const EventsId As String = "06C156DD-0ABA-437e-9EE0-C1CE2CA34033"
End Class

标签: vb.net com
3条回答
狗以群分
2楼-- · 2019-07-15 11:15

By explicitly putting attributes on the classes and enumerations that you want exposed you can prevent things like helper classes, internal tools, or internal classes that should not be exposed from being exposed. This is the recommended way from Microsoft to do it...and when they recommend something, it usually means that if you don't do it, your program may break in the future. :)

Checking "make COM visible" and "register for COM interop" is the simple method for making COM visible objects, but is not recommended. This will add the overhead for every class visible - even ones that you may not want.

查看更多
女痞
3楼-- · 2019-07-15 11:31

The ComClass attribute is specific to Visual Basic and is intended to simplify the creation of COM objects in .Net code. When the compiler sees this attribute it do some of the tedious work under the hood that must be manually done in C#. In summary, it's a shortcut for Visual Basic Code for creating COM objects.

Here's a great article on what this provides over doing the same in C#:

查看更多
Evening l夕情丶
4楼-- · 2019-07-15 11:36

Will VB.NET automatically generate ComClass attribute and guids?

Yes, if you use VB.NET COMClass template to create a class, COMClassAttribute and those GUIDs will be automatically generated.

Detail in MSDN Section "To create a COM object by using the COM class template"

查看更多
登录 后发表回答