![](/img/trans.png)
[英]Using Reflection Invoke static generic method passing a Lamba as parameter
[英]Reflection: invoke a method with generic parameter
我是大家
我在使用反射调用方法时遇到了一些问题。
方法标志是
public T Create<T, TK>(TK parent, T newItem, bool updateStatistics = true, bool silent = false)
where T : class
where TK : class;
public T Create<T, TK>(TK parent, string newName, Language language = null, bool updateStatistics = true, bool silent = false)
where T : class
where TK : class;
我想使用第二个重载。
我的代码是
typeof(ObjectType).GetMethod("Create")
.MakeGenericMethod(new Type[] { typeof(Item), typeof(TKparent) })
.Invoke(_objectInstance, new object[] { parent, name, _language, true, false });
其中Item是一个类,TKparent是一个类型变量,parent是一个TKparent实例。
我得到一个System.Reflection.AmbiguousMatchException。
我认为这个问题与泛型有关
我也尝试了这个:
typeof(ObjectType).GetMethod("Create", new Type[] { typeof(TKparent), typeof(string), typeof(Globalization.Language), typeof(bool), typeof(bool) })
.MakeGenericMethod(new Type[] { typeof(Item), typeof(Tparent) })
.Invoke(_objectInstance, new object[] { parent, name, _language, true, false });
但在这种情况下,我得到一个System.NullReferenceException(找不到方法)
谁能帮到这个,我生气了!
谢谢
问题是GetMethod
在你告诉它需要哪个重载之前找到了多个带有该鬃毛的方法。 允许您传入类型数组的GetMethod
重载适用于非泛型方法,但由于参数是通用的,因此您无法使用它。
你需要调用GetMethods
并过滤到你想要的那个:
var methods = typeof(ObjectType).GetMethods();
var method = methods.Single(mi => mi.Name=="Create" && mi.GetParameters().Count()==5);
method.MakeGenericMethod(new Type[] { typeof(Item), typeof(TKparent) })
.Invoke(_objectInstance, new object[] { parent, name, _language, true, false });
如果你愿意,你可以明显地内联所有这些,但是如果你把它分成不同的行,它会使调试变得更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.