反射:调用具有泛型参数的方法

Ale*_*lex 5 c# generics reflection invoke

我大家,

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

方法标志是

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;
Run Code Online (Sandbox Code Playgroud)

我想使用第二个重载。

我的代码是

typeof(ObjectType).GetMethod("Create")
            .MakeGenericMethod(new Type[] { typeof(Item), typeof(TKparent) })
            .Invoke(_objectInstance, new object[] { parent, name, _language, true, false });
Run Code Online (Sandbox Code Playgroud)

其中 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 });
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,我得到一个 System.NullReferenceException(找不到方法)

谁能帮帮我,我快疯了!

谢谢你

D S*_*ley 3

问题在于,在您告诉它您想要哪个重载之前,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 });
Run Code Online (Sandbox Code Playgroud)

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