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

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 是一个 class,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 });

如果你愿意,你显然可以内联所有这些,但如果你将它分成单独的行,它会使调试更容易。