簡體   English   中英

通過帶有委托參數的反射調用泛型方法的問題

[英]Issues in calling generic method through reflection with a delegate parameter

我已經搞了一個多小時了,似乎無法正確解決。 這是我遇到的例外之一:

錯誤:無法將類型為System.Func1[System.Object]對象轉換為類型為System.Func1[System.Collections.Generic.IEnumerable1[System.Collections.Generic.IEnumerable1[System.Object]]]

基本上我有一個通用的工廠方法,看起來像這樣

ReturnItem<TResult> CreateOutput<T, TResult>(Func<IEnumerable<T>> postBack,
    Processor manager) where TResult : class;

並且我嘗試進行反思,但是Func<IEnumerable<T>>導致了我的問題。 這是我嘗試調用的代碼:

var infer = Factory.CreateReturnInference(); //Keypair value (type, type) is NOT an NormalOutputFactory in this instance
Func<object> callBack = () => subTypes;

var toRun = Factory.GetType()
            .GetMethod("CreateOutput", BindingFlags.Public | BindingFlags.Instance)
            .MakeGenericMethod(infer.Key, infer.Value)
            .Invoke(Factory,
                new object[] {callBack, Manager}) as
            ReturnItem<object>;

Factory.CreateReturnInference返回的密鑰對值用於指定通用參數,並且只是為了使其實現清晰(警告非常難看的代碼,違反了其他交易的開盤價:)):

public KeyValuePair<Type, Type> CreateReturnInference()
    {
        return this is NormalOutputFactory
            ? new KeyValuePair<Type, Type>(typeof (object), typeof (Log))
            : new KeyValuePair<Type, Type>(typeof (IEnumerable<object>), typeof (Enum));
    } 

普遍的問題是:通過反射調用泛型方法時,如何指定Func參數?

問題是您沒有正確指定Func<T>參數。 換句話說,您傳遞給CreateOutput方法的是錯誤的類型。 當您這樣做時:

MakeGenericMethod(infer.Key, infer.Value)

方法的類型參數

ReturnItem<TResult> CreateOutput<T, TResult>(Func<IEnumerable<T>> postBack, ...)

您傳遞的是typeof(IEnumerable<object>)typeof(Enum) 因為你做

return new newKeyValuePair<Type, Type>(typeof(IEnumerable<object>), typeof(Enum));

因此,您嘗試創建的CreateOutput方法具有如下簽名:

ReturnItem<Enum> CreateOutput(Func<IEnumerable<IEnumerable<object>>> postBack, ...)

換句話說, T成為IEnumerable<object>TResult成為Enum 但是傳遞給您用來調用構造的泛型方法callbackFunc參數的定義如下:

Func<object> callBack = () => subTypes;

您的解決方案是:

1)像這樣更改callback簽名:

Func<IEnumerable<IEnumerable<object>>> callBack = () => subTypes;

2)或通過調整鍵值對函數來更改通用方法的參數類型。

Func<IEnumerable<object>> callBack = () => subTypes;

public KeyValuePair<Type, Type> CreateReturnInference()
{
    return ... new KeyValuePair<Type, Type>(typeof(object), typeof(Enum));
} 

我認為第二個是您想要的,但是我不確定。

我設法通過將KeyValuePair的返回值更改為此來解決該問題:

public KeyValuePair<Type, Type> CreateReturnInference()
{
    return this is NormalOutputFactory
        ? new KeyValuePair<Type, Type>(typeof (object), typeof (object))
        : new KeyValuePair<Type, Type>(typeof (IEnumerable<object>), typeof (object));
} 

仍然不太樂意這樣做,但是解決了這個問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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