Access properties in System.Collections.Generic.List

Using Mono.Cecil , I can iterate over fields on System.Collections.Generic.List ( _items , _size , _version , etc.), however, if I try to use them, I always get an exception

Member 'T [] System.Collections.Generic.List`1 :: _ items' is declared in another module and must be imported

I have two questions regarding this:

  • Is it impossible to access the generic generic fields?
  • If possible, what would the import expression look like for him?

I have successfully accessed private members on objects (until they are generated by the compiler), so I assume that (1) is fine. I have also successfully imported things, although I admit that my understanding of how imports work is shaky (aka β€œif it gives an error, just try importing it”).

+6
source share
1 answer

You need to import FieldDefinition into ModuleDefinition before writing an IL pointing to it.

So, looking at your code, it will be something like this.

 var fieldReference = ModuleDefinition.Import(field); Action<Collection<Instruction>> load = collection => collection.AddI(OpCodes.Ldfld, fieldReference); 

I also note that you have another error. By the time you are in the above code, you have lost the context of type arguments. So you are trying to name something on List<T> instead of something like List<MyClass> . But you can ask one more question if you cannot solve this problem :)

+3
source

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


All Articles