簡體   English   中英

在作為參數 C# 傳遞的 function 中使用參數

[英]Using params in a function passed as parameter C#

這可能有點令人困惑,所以我將嘗試解釋我的情況。

我有一個 function 接收另一個 function 作為參數,但后者可以有不同的參數。

我試過這樣的事情:

public static async Task<IEnumerable<T>> MyFunction<T>(
    Func<int, int, params DateTime[], SomeEntity> mySmallerFunction)
{
    ...something here;
}

我想使用“參數”,因為我必須在兩種不同的情況下使用 MyFunction:

SomeEntity mySmallerFunction(int, int, DateTime)

SomeEntity mySmallerFunction(int, int, DateTime, DateTime)

事實上,Visual Studio 指責錯誤“預期類型”和“語法錯誤,預期 'char'”。 我不知道我做錯了什么,或者我想做的事情是否可能。 誰能幫我解決我的問題?

正如 JonasH 在他的回答中解釋的那樣,編譯器不支持這一點。 讓我建議一個替代解決方案。 讓我們保持 MyFunction 原樣(但沒有params ):

public static async Task<IEnumerable<T>> MyFunction<T>(
    Func<int, int, DateTime[], SomeEntity> mySmallerFunction)
{
    ...something here;
}

現在在調用MyFunction 時,您可以創建一個lambda 表達式,該表達式具有所需的語法並將數組轉換為參數:

// Calling it with mySmallerFunction(int, int, DateTime)
MyFunction((i1, i2, dts) => mySmallerFunction(i1, i2, dts[0]));

// Calling it with mySmallerFunction(int, int, DateTime, DateTime)
MyFunction((i1, i2, dts) => mySmallerFunction(i1, i2, dts[0], dts[1]));

顯然,這假設您的業務邏輯確保 MyFunction足夠聰明,可以知道它是否需要傳遞一個元素或兩個元素的數組。


或者,您可以聲明 MyFunction 始終傳遞兩個DateTimes 並在適當時忽略第二個值:

public static async Task<IEnumerable<T>> MyFunction<T>(
    Func<int, int, DateTime, DateTime, SomeEntity> mySmallerFunction)
{
    ...something here;
}

// Calling it with mySmallerFunction(int, int, DateTime)
MyFunction((i1, i2, dt1, dt2) => mySmallerFunction(i1, i2, dt1));

// Calling it with mySmallerFunction(int, int, DateTime, DateTime)
MyFunction(mySmallerFunction);

顯然,您也可以將該轉換邏輯移動到第二個 MyFunction 重載中:

public static async Task<IEnumerable<T>> MyFunction<T>(
    Func<int, int, DateTime, SomeEntity> mySmallerFunction)
{
    return MyFunction<T>((i1, i2, dt1, dt2) => mySmallerFunction(i1, i2, dt1));
}

public static async Task<IEnumerable<T>> MyFunction<T>(
    Func<int, int, DateTime, DateTime, SomeEntity> mySmallerFunction)
{
    ...something here;
}

暫無
暫無

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

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