Will VB.NET automatically generate ComClass attribute and guids?

Will VB.NET automatically generate ComClass attribute and guids?

岁吢 发布于 2021-11-29 字数 787 浏览 736 回复 3 原文

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

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

卸妝后依然美 2022-06-07 3 楼

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"

快乐很简单 2022-06-07 2 楼

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.

生生不灭 2022-06-07 1 楼

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#: