开发者

Preventing GetType from throwing exceptions on internal types

Is there any way to prevent o.GetType() from throwing an exception when called on an object whose type is internal and resides in another assembly?

I am wrapping a COM based API inside a .Net assembly so that it is possible to benefit from more native .Net integration (Collection interfaces, streams, exceptions etc.). The collections the original API has have been wrapped in the following way:

internal class ComItems : IList<ComItem>
{
    internal ComItems(ComApi.ComItems unmanaged) { this.unmanaged = unmanaged; }

    public void Add(ComItem item) {
        this.unmanaged.Add(-1, item.ToUnmanaged());
    }

    // Rest of the IList implementation
}

Since there are several of these collections I wish to expose them as instances of IList<T> and keep the original type as internal so they don't clutter the namespaces. Th开发者_JS百科e issue here is that calling GetType() on one of the returned IList<T> objects results in an exception since the underlying type is an internal one.

Are there any ways to prevent this exception?

Is there any way to force GetType to return typeof(IList<T>) instead? Not sure if this is any better though since it differe from the standard behaviour.

I understand one alternative to reducing clutter would be separating the collections into another namespace. Unfortunately some of the collections contain extra methods and are exposed as public types. This would either mean that the collections are divided behind two different namespaces (Main one and 'internal') or then they are all behind the 'internal' one and when people need those specialized collections they'll import that namespaces and those simple collections clutter IntelliSense again.


GetType should work fine on internal types from other assemblies. What exception are you seeing?

Are you sure it's the call to GetType itself which is throwing an exception, and not some subsequent use of the type? If you could give a short but complete program demonstrating the problem, that would help a lot.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜