0

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...).

Community
  • 1
  • 1
JesseBuesking
  • 6,496
  • 4
  • 44
  • 89
  • I know what you are getting at but you will need some more context here to make it a viable question for StackOverflow. a code snippet/unit test and the error you get would be best – Simon May 02 '13 at 03:40
  • 1
    You should add a reference to `Mono.Cecil.Rocks` assembly, and use `TypeReferenceRocks.MakeGenericInstanceType` extension method. – Lex Li May 03 '13 at 06:36

0 Answers0