问题
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