TypeBuilder.GetMethod on TypeBuilder
source link: https://www.codesd.com/item/typebuilder-getmethod-on-typebuilder.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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_Default");
// 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"));
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK