COM服务器如何使用不同的ComInterfaceType枚举封送C#类库中的可空?

我听说Nullable是一个C#generics类,它不能与COM一起使用 – 就像任何其他generics类一样。

好吧,在我的C#类库中,我有:

 [InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("2FCEF713-CD2E-4ACB-A9CE-E57E7F51E72E")] public interface ICOMClass { int? GetNullable(); } [ClassInterface(ClassInterfaceType.None)] [Guid("57BBEC44-C6E6-4E14-989A-B6DB7CF6FBEB")] public class COMClass : ICOMClass { public int? GetNullable() { int? hello = null; return hello; } } 

令人惊讶的是 ,编译并且我能够在VBE中附加对我的COMClass库的引用。

我知道:

  • VBA 不在对象浏览器的成员列表中列出.GetNullable() (即使显示隐藏的成员已勾选)
  • VBA没有在智能下拉列表中列出.GetNullable()

但为什么:

 Dim c as new COMClass c.GetNullable 

不抛出相当期望的Object doesn't support this property or method

而不是:

 c.NonExistingMethod 

有人可以解释为什么吗

我怀疑它与ComInterfaceType Enumeration有关,因为

  • 两者: InterfaceIsDualInterfaceIsIDispatch就像我上面描述的那样

但:

  • InterfaceIsIUnknown实际上似乎没有编组/ 触摸 GetNullable()并且抛出了预期的错误…

谁能解释这种行为?

好吧,它编译。 但是,当您尝试为DLL创建类型库时,您知道自己遇到了麻烦:

 C:\projects2\ClassLibrary38\bin\Debug>tlbexp ClassLibrary38.dll Microsoft (R) .NET Framework Assembly to Type Library Converter 4.0.30319.33440 Copyright (C) Microsoft Corporation. All rights reserved. TlbExp : warning TX8013117D : Type library exporter warning processing 'ICOMClas s.GetNullable(#0), ClassLibrary38'. Warning: Type library exporter encountered a generic type instance in a signature. Generic code may not be exported to COM. Assembly exported to 'C:\projects2\ClassLibrary38\bin\Debug\ClassLibrary38.tlb' 

您可以通过在类型库上运行OleView.exe来查看它。 这是您的界面的样子:

 [ odl, uuid(2FCEF713-CD2E-4ACB-A9CE-E57E7F51E72E), version(1.0), dual, oleautomation, custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, "ICOMClass") ] interface ICOMClass : IDispatch { }; 

没什么,nada,zippo。 Microsoft编程人员在编写诊断消息时有时过于友好。 它不仅仅是“可能不是”,而是“不会”。

这不会起作用。 它可以通过后期绑定找到方法无济于事,返回值无法正确解释, Nullable不是[ComVisible]。 作为替代方案,考虑到COM总是必须具有“可空性”的概念,在VBA中得到强烈支持,这在很大程度上取决于它。 变体可以存储vtNull或vtEmpty以指示未设置值。 它是C#代码中的对象