这应该工作:
var tb = mb.DefineType("Test", TypeAttributes.Public);
var iface = typeof(IComparable<>).MakeGenericType(tb);
tb.AddInterfaceImplementation(iface);
var meb = tb.DefineMethod("CompareTo", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), new [] { tb });
var il = meb.GetILGenerator();
il.ThrowException(typeof(Exception));
var type = tb.CreateType();
幸运的是,从TypeBuilder类型继承,所以你可以在MakeGenericType
使用它。
作为验证,这个工程:
var o1 = Activator.CreateInstance(type);
var o2 = Activator.CreateInstance(type);
typeof(IComparable<>).MakeGenericType(o1.GetType()).GetMethod("CompareTo").Invoke(o1, new [] { o2 }).Dump();
您不必生成的方法绑定到任何方式的界面,这是不够的,他们的签名是一样的。做明确的接口实现可能有点棘手,但你不应该需要这样做。
希望我有时间玩这个..但我期待着别人回答! –
我看到一个方法['addInterfaceImplementation'](http://msdn.microsoft.com/zh-cn/library/system.reflection.emit.typebuilder.addinterfaceimplementation(v = vs.110).aspx),你可以调用在您构建新类型之后,您的['TypeBuilder'](http://msdn.microsoft.com/zh-CN/library/system.reflection.emit.typebuilder(v = vs.110).aspx)。之后你不能使用这种方法将“Comparable''添加到你的类型中吗? –
@JeroenVannevel我不认为这是允许的。我很肯定你只能调用一次'CreateType'。 – Anthony