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)
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:
AppDomain.DefineDynamicAssembly
DynamicMethod
once for each set of type argumentsActually 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With