Cómo utilizar OpCodes.Call para generar este código

Esta pregunta está relacionada con: Transmitir elementos de una colección con generación de código

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

Aquí hay un ejemplo de lo que estoy tratando de hacer:

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(); } }
}

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

preguntado el 01 de febrero de 12 a las 22:02

2 Respuestas

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

Respondido 02 Feb 12, 02:02

I think this is great advice. - usr

This is indeed a good advice BUT I still have no idea how to generate the IL code that I see (I added the two lines that I think I need to generate as Edit 1) - W3Max

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

Respondido 02 Feb 12, 09:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.