如何在Action中传递参数?

Jop*_*Jop 66 .net c# action

private void Include(IList<string> includes, Action action)
{
    if (includes != null)
    {
        foreach (var include in includes)
            action(<add include here>);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想这样称呼它

this.Include(includes, _context.Cars.Include(<NEED TO PASS each include to here>));
Run Code Online (Sandbox Code Playgroud)

这个想法是将每个包含传递给方法.

The*_*ter 95

如果您知道要传递的参数,请Action<T>选择类型.例:

void LoopMethod (Action<int> code, int count) {
     for (int i = 0; i < count; i++) {
         code(i);
     }
}
Run Code Online (Sandbox Code Playgroud)

如果要将参数传递给方法,请使方法通用:

void LoopMethod<T> (Action<T> code, int count, T paramater) {
     for (int i = 0; i < count; i++) {
         code(paramater);
     }
}
Run Code Online (Sandbox Code Playgroud)

和来电者代码:

Action<string> s = Console.WriteLine;
LoopMethod(s, 10, "Hello World");
Run Code Online (Sandbox Code Playgroud)

更新.您的代码应如下所示:

private void Include(IList<string> includes, Action<string> action)
{
    if (includes != null)
    {
         foreach (var include in includes)
             action(include);
    }
}

public void test()
{
    Action<string> dg = (s) => {
        _context.Cars.Include(s);
    };
    this.Include(includes, dg);
}
Run Code Online (Sandbox Code Playgroud)


SLa*_*aks 11

你正在寻找Action<T>,它需要一个参数.


ne2*_*mar 7

脏技巧:您也可以使用lambda表达式传递您想要的任何代码,包括带参数的调用.

this.Include(includes, () =>
{
    _context.Cars.Include(<parameters>);
});
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个,因为我有一个实用程序类已经在很多地方使用,但不接受 `Action&lt;T&gt;` - 这让我仍然可以使用它而无需修改。 (2认同)