反射:使用通用参数调用方法

亚历克斯

我每个人

我在调用带有反射的方法时遇到一些问题。

方法标志是

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是类型变量,父对象是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 });

显然,如果需要,可以内联所有这些内容,但是如果将其分成单独的行,则调试会更容易。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章