How to use OpCodes.Call to generate this code

匆匆过客 提交于 2019-12-12 04:54:20

问题


This question is related to: Casting items of a collection with code generation

Since the previous question was not clear enough, here is what I need help with precisely.

How to use OpCodes.Call to generate this code:

return Enumerable.ToList<Potato>(Eumerable.Cast<Potato>(_proxyPotatoes));

Here is an example of what I'm trying to do:

public class Potato
{
}

public class ProxyPotato : Potato
{    
}

public class Stew
{
  private ICollection<ProxyPotato> _proxyPotatoes;

  //This is the code I would like to generate (specialy the cast part)
  public ICollection<Potato> Potatoes { get { return _proxyPotatoes.Cast<Potato>().ToList(); } }
}

Edit 1

After the suggestion of @zmbq here is the two line of IL i need to generate:

call class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0> [System.Core]System.Linq.Enumerable::Cast<class Maxime.Potato>(class [mscorlib]System.Collections.IEnumerable)

call class [mscorlib]System.Collections.Generic.List`1<!!0> [System.Core]System.Linq.Enumerable::ToList<class Maxime.Potato>(class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0>)

回答1:


The two method calls should look something like:

ilg.Emit(OpCodes.Call, typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(typeof(Potato)));
ilg.Emit(OpCodes.Call, typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(typeof(Potato)));



回答2:


I have a suggestion - write the code in C#, compile it and use ILDASM to see exactly what you need to Emit.



来源:https://stackoverflow.com/questions/9104085/how-to-use-opcodes-call-to-generate-this-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!