如何在Action中传递参数?


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

我想这样称呼

this.Include(includes, _context.Cars.Include(<NEED TO PASS each include to here>));

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


Action只是一个Action还是它是Action<T>或其他任何变体?您要多少个参数?
BoltClock

看起来您已经通过includes参数传递了include 。您是否想将includes列表的每个成员传递给action?如果是这样,只需通过_context.Cars.Include(不带括号)。
itowlson

是这个想法是通过每个包括所述方法_context.Cars.Include()
Jop的

@itowlson仍然无法实现这一目标。
Jop的

您看到什么错误?该_context.Cars.Include方法的签名是什么?Scrum Meister的更新后的答案对我来说似乎很正确,但是我猜想Cars.Include方法可能需要调整以采用字符串...?
itowlson

Answers:


110

如果知道要传递的参数,请Action<T>为类型输入。例:

void LoopMethod (Action<int> code, int count) {
     for (int i = 0; i < count; i++) {
         code(i);
     }
}

如果希望将参数传递给您的方法,请使该方法通用:

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

和调用者代码:

Action<string> s = Console.WriteLine;
LoopMethod(s, 10, "Hello World");

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

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);
}

想法是通过每个包括所述方法_context.Cars.Include()
Jop的

使用此代码(更新后的代码),获取错误:'System.Data.Objects.ObjectQuery <Repository.Entity.Car> System.Data.Objects.ObjectQuery <Repository.Entity.Car> .Include(string)'返回错误键入
Jop的

@jop已更新,构建一个新的Action<string>委托,该委托调用Cars.Include。另外,您的自定义Include方法可以接受Func<string, whatever type Cars.Include() returns>
The Scrum Meister

约定是通用变体应具有名为arg的参数T,而不是参数。
magnusarinell


10

肮脏的把戏:您也可以使用lambda表达式来传递您想要的任何代码,包括带有参数的调用。

this.Include(includes, () =>
{
    _context.Cars.Include(<parameters>);
});

我之所以喜欢它,是因为我有一个已经在许多地方使用的实用程序类,而该类却不接受Action<T>-这使我仍然可以不经修改地使用它。
GregHNZ
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.