How To Expose a DIctionary<> to COM Interop

蓝咒 提交于 2019-12-10 15:18:10

问题


I have an Interface that is defined something along these lines:

Interface foo
  {
  int someProperty {get; set;}
  Dictionary<string, object> Items;
  }

The concrete class that implements this interface needs to be registered for COM Interop. Everything compiles and the assemblies seem to register OK, but then when trying to create the COM object (e.g. from PowerShell) I get an error.

This seems to be related to the generic Dictionary<> class that I'm using. So here is the question:

  1. Is it even possible to expose generic collections through COM Interop?
  2. If yes, then how is it done?
  3. If no, then what's the workaround?

回答1:


I ended up here via a Google search and, ha ha, I should have guessed this would come from you.

As far as I know generics can't be marshalled through COM with the standard marshallers. What I do know is that an ArrayList in C# turns into a "standard" collection in COM, usable by VBScript, VB, JScript 5.x, etc. But since we're working toward a common goal, I'm going to play with some other aggregate types and see what happens.




回答2:


Generics can't be COM-visible, VS should give you a compile-time warning about this.

Another solution could be to make the dictionary private and expose methods to add/remove/fetch items to/from the dictionary:

public interface ComVisibleFoo
{
    int SomeProperty { get; set; }

    //Dictionary<string, object> Items; // can't be COM-visible

    void AddItem(string key, object value);
    void RemoveItem(string key);
    object Item(string key);
}


来源:https://stackoverflow.com/questions/1296362/how-to-expose-a-dictionary-to-com-interop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!