Using Generic lists on serviced component

2019-06-09 17:38发布

I'm trying to use a generic List as a property on a ServicedComponent class...

public class MyCOM : ServicedComponent {
    public enum MyEnumType {
        Value1, Value2, Value3
    }
    public List<MyEnumType> MyList { private set; get; }
    public MyCOM()
    {
        MyList = new List<MyEnumType>();
    }
}

The code compiles without errors but when I try to use the MyList property on the com object from a different class no values get added to the list. Google "told me" that I can't use Generics on Components but I'm yet to find a good explanation why that is and a good solution to the problem.

Can someone help me out?

1条回答
一夜七次
2楼-- · 2019-06-09 18:04

From MSDN:

Interoperating Using Generic Types

The COM model does not support the concept of generic types. Consequently, generic types cannot be used directly for COM interop.

The answer why generics are not supported is very simple, generics are types that are constructed at runtime, and because of this there's no static interface declaraion to the constructed type that COM can refer to. In your case List< MyEnumType > doesn't exist as a type Until the CLR constructs it, so COM can't refer to it with and identifier (GUID).

This is where the workaround comes from, if your generic types implement a non generic interface, then they can be used for com interop using the non generic interface.

查看更多
登录 后发表回答