问题
Is it possible to define a DynamicMethod with generic type parameters? The MethodBuilder class has the DefineGenericParameters method. Does the DynamicMethod have a counterpart? For example is it possible to create method with a signature like the one given blow using DynamicMethod?
void T Foo<T>(T a1, int a2)
回答1:
Actually there is a way, it's not exactly generic but you'll get the idea:
public delegate T Foo<T>(T a1, int a2);
public class Dynamic<T>
{
public static readonly Foo<T> Foo = GenerateFoo<T>();
private static Foo<V> GenerateFoo<V>()
{
Type[] args = { typeof(V), typeof(int)};
DynamicMethod method =
new DynamicMethod("FooDynamic", typeof(V), args);
// emit it
return (Foo<V>)method.CreateDelegate(typeof(Foo<V>));
}
}
You can call it like this:
Dynamic<double>.Foo(1.0, 3);
回答2:
This doesn't appear to be possible: as you've seen DynamicMethod
has no DefineGenericParameters
method, and it inherits MakeGenericMethod
from its MethodInfo
base class, which just throws NotSupportedException
.
A couple of possibilities:
- Define a whole dynamic assembly using
AppDomain.DefineDynamicAssembly
- Do generics yourself, by generating the same
DynamicMethod
once for each set of type arguments
来源:https://stackoverflow.com/questions/788618/dynamicmethod-with-generic-type-parameters