Maintaining context of type arguments with Mono.Cecil

半世苍凉 提交于 2019-12-08 13:31:31

问题


After learning how to properly access the fields and properties of a List with Mono.Cecil, it was pointed out that you need to make sure that the context of the type arguments is maintained on the List object that you're working with (which makes sense).

What's the proper way to do this?

Edit (based on @Simon's request)

Given you have a TypeReference for a list, for example

System.Collections.Generic.List`1<MyNamespace.MyObject>

and you want to access it's fields, you'll actually need a TypeDefinition for this list. When you attempt to Resolve your TypeReference, you end up losing the type arguments that were a part of the original TypeReference (aka your new TypeDefinition will now be for

System.Collections.Generic.List`1

which will have a GenericParameter of T).

I have attempted to re-apply the type arguments via code like the following

var resolve = myList.Resolve();
resolve.GenericParameters.Clear();
foreach (var p in (myList as GenericInstanceType).GenericArguments)
{
    var gp = new GenericParameter(p.FullName, p.GetElementType().Resolve());
    resolve.GenericParameters.Add(gp);
}

This doesn't work, leading to an

Member 'MyNamespace.MyObject' is declared in another module and needs to be 
imported

error. (If you didn't attempt to repopulate in this fashion, the error would instead be Member 'T' is declared...).

来源:https://stackoverflow.com/questions/16329710/maintaining-context-of-type-arguments-with-mono-cecil

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