簡體   English   中英

反射:使用泛型參數調用方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM