简体   繁体   中英

Reflection.Emit: Get a MethodInfo for a constructed type having GenericTypeParameterBuilder type parameter

I'm trying to Reflection.Emit a generic class that implements a generic interface constructed with the class's generic parameter, like eg this:

class Foo<U>: IEquatable<U>
{
    bool IEquatable<U>.Equals(U other) { /* ... */ }
}

I'm struggling to get a MethodInfo for the IEquatable<U>.Equals(U) method.

Reflecting the constructed type IEquatable<U> throws a NotSupportedException because U is a GenericTypeParameterBuilder , whereas TypeBuilder.GetMethod(IEquatable<U>, IEquatable<T>.Equals(T)) returns a weird IEquatable<U>.Equals(T) method.

Any help appreciated!

Test code:

// define class Foo<U>
var tb = moduleBuilder.DefineType("Foo");
var genParams = tb.DefineGenericParameters("U");

// IEquatable<T>.Equals(T) method
var miEqualsT = typeof(IEquatable<>).GetMethod("Equals", typeof(IEquatable<>).GetGenericArguments());

// IEquatable<U> constructed type
var iEquatableU = typeof(IEquatable<>).MakeGenericType(genParams);

// now trying to get IEquatable<U>.Equals(U) method
MethodInfo miEqualsU;
try { miEqualsU = iEquatableU.GetMethod("Equals", genParams); }
catch (NotSupportedException) { Console.WriteLine("Reflecting constructed interface not supported."); }

miEqualsU = TypeBuilder.GetMethod(iEquatableU, miEqualsT);
var declaringType =$"{miEqualsU.DeclaringType.Name}<{miEqualsU.DeclaringType.GenericTypeArguments[0].Name}>";
var parameterType = miEqualsU.GetParameters()[0].ParameterType;
Console.WriteLine($"TypeBuilder.GetMethod() returns {declaringType}.{miEqualsU.Name}({parameterType.Name})");

// OUTPUT:
// Reflecting constructed interface not supported.
// TypeBuilder.GetMethod() returns IEquatable`1<U>.Equals(T)

You've got the correct method with miEqualsT already. Here's how you'd implement the interface with the method:

var assemblyName = new AssemblyName { Name = "asd" };
var moduleBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run).DefineDynamicModule(assemblyName.Name);

var tb = moduleBuilder.DefineType("Foo");
var genParams = tb.DefineGenericParameters("U");
var miEqualsT = typeof(IEquatable<>).GetMethod("Equals", typeof(IEquatable<>).GetGenericArguments());

var myMethod = tb.DefineMethod("Equals", MethodAttributes.Public | MethodAttributes.Virtual, typeof(bool), genParams);

var il = myMethod.GetILGenerator();
il.Emit(OpCodes.Ldstr, "I was invoked!");
il.Emit(OpCodes.Call, GetMethod<string>(a => Console.WriteLine(a)));
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Ret);

tb.AddInterfaceImplementation(typeof(IEquatable<>).MakeGener‌​icType(genParams));
tb.DefineMethodOverride(myMethod, miEqualsT);

var t = tb.CreateType();

//Hack for demonstration
private MethodInfo GetMethod<T>(Expression<Action<T>> thing)
{
    return ((thing as LambdaExpression).Body as MethodCallExpression).Method;
}

And then using it:

var genericType = t.MakeGenericType(typeof(int));
var tObj = Activator.CreateInstance(genericType);

var method = genericType.GetMethods()
    .Where(m => m.Name == "Equals" && m.DeclaringType == genericType)
    .First();

method.Invoke(tObj, new object[] { 5 });

Or:

var tObj = Activator.CreateInstance(genericType);
DoIt(tObj as IEquatable<int>);

private void DoIt(IEquatable<int> obj)
{
    obj.Equals(5);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM