问题
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