TypeBuilder.GetMethod on TypeBuilder
TypeBuilder.GetMethod
allows you to get a method on a generic type closed by a TypeBuilder
so it lets me to the following:
TypeBuilder tb = ....
// this would throw a NotSupportedException :
// var ec = typeof(EqualityComparer<>).
// MakeGenericType(tb).GetMethod("get_Default");
// this works:
var ec = TypeBuilder.GetMethod(tb, typeof(EqualityComparer<>).
GetMethod("get_Default");
What doesn't work (and I can't figure out how to make it work yet) is this:
Type collectionOf = typeof(ICollection<>).MakeGenericType(tb);
// throws: 'Type must be a type provided by the runtime.
// Parameter name: types'
var colEc = TypeBuilder.GetMethod(collectionOf, typeof(EqualityComparer<>).
GetMethod("get_Defaul开发者_Go百科t");
// throws NotSupportedException
colEc = typeof(EqualityComparer<>).MakeGenericType(collectionOf).
GetMethod("get_Default");
Anyone know the answer (I hope it's 42)...?
It's not completely clear to me what you're trying to do (it looks like you're missing some parentheses, among other issues), but if you're trying to get a MethodInfo
for EqualityComparer<ICollection<YourType>>.get_Default
, this works for me:
var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("test"),
AssemblyBuilderAccess.Run);
var mb = ab.DefineDynamicModule("test");
var tb = mb.DefineType("TestType");
var ico = typeof(ICollection<>);
var eq = typeof(EqualityComparer<>);
var m = TypeBuilder.GetMethod(eq.MakeGenericType(ico.MakeGenericType(tb)), eq.GetMethod("get_Default"));
Like said earlier, you cannot do reflection on types that have not been created yet.
You need to either keep track of the methods, or ensure that you have a runtime type that is returned from called TypeBuilder.CreaterType()
. TypeBuilder
'conveniently' does keep track of the created runtime type for you if it has already been created.
This goes for almost every reflection operation in Reflection.Emit
types, not just TypeBuilder
.
Update:
I have not noticed TypeBuilder.GetMethod
before, so I am probably wrong above. Will find out the detail. :)
Update 2: Possible solution
Does the following work?
typeof(EqualityComparer<>).GetMethod("get_Default").MakeGenericMethod(tb)
Should be testing :(
精彩评论