本文介绍了访问System.Collections.Generic.List上的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Mono.Cecil ,我可以遍历System.Collections.Generic.List(_items_size_version等)上的字段,但是如果我尝试使用它们,我总是得到例外

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

对此我有两个问题:

  1. 是否无法访问泛型的基础字段?
  2. 如果可能的话,import语句的外观如何?

我已经成功访问​​了对象的私有成员(只要它们不是由编译器生成的),因此我假设(1)可以.我也成功导入了东西,尽管我承认我对导入工作方式的理解是不稳定的(又名如果出现错误,请尝试导入它").

I've successfully accessed private members on objects (as long as they're not compiler generated), so I'm assuming (1) is ok. I've also successfully imported things, although I admit my understanding of how the import is working is shaky (aka "if it gives an error, just try importing it").

推荐答案

在编写指向它的IL之前,需要将FieldDefinition导入到ModuleDefinition中.

You need to import the FieldDefinition into the ModuleDefinition before writing IL that points to it.

因此,在查看您的代码之后,将是这样的.

So after looking at your code it would be something like this.

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

我还注意到您还有另一个错误.到您在上面的代码中时,您已经失去了类型参数的上下文.因此,您尝试在List<T>上调用某个内容,而不是在List<MyClass>上调用某个内容.但是,如果您不能解决该问题,则可以提出另一个SO问题:)

I also note that you have another bug. By the time you are in the above code you have lost the context of the type arguments. So you are trying to call something on List<T> instead of something like List<MyClass>. But you can raise another SO question if you cant solve that one :)

这篇关于访问System.Collections.Generic.List上的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 03:02