Maintaining the context of type arguments with Mono.Cecil

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

What is the right way to do this?

Edit (based on @Simon request)

If you have a TypeReference for a list like

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

and you want to access these fields, you really need TypeDefinition for this list. When you try to Resolve your TypeReference , you lose the type arguments that were part of the original TypeReference (otherwise your new TypeDefinition will now be for

 System.Collections.Generic.List`1 

which will have a GenericParameter of T ).

I tried re-applying type arguments through code, as shown below:

 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 does not work, leading to

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

error. (If you did not try to refill this way, Member 'T' is declared... instead of an error Member 'T' is declared... ).

0
source share

Source: https://habr.com/ru/post/943494/


All Articles