繁体   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