【问题标题】:How can I pass a parameter in Action?如何在 Action 中传递参数?
【发布时间】:2011-06-25 07:54:59
【问题描述】:
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&lt;T&gt; 或任何其他变体?你要多少参数?
  • 看起来您已经通过 includes 参数传递了包含。是否要将includes 列表中的每个成员传递给action?如果是这样,只需传递_context.Cars.Include(不带括号)。
  • 是的,想法是将每个包含传递给方法 _context.Cars.Include()
  • 您看到了什么错误? _context.Cars.Include 方法的签名是什么? Scrum Meister 的更新答案在我看来是正确的,但我猜 Cars.Include 方法可能需要调整以获取字符串...?
  • 出现错误:'System.Data.Objects.ObjectQuery System.Data.Objects.ObjectQuery.Include(string)' 返回错误类型。签名是:public ObjectQuery Include(string path);

标签: c# .net action


【解决方案1】:

如果您知道要传递的参数,请使用Action&lt;T&gt; 作为类型。示例:

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()
  • 使用此代码(来自更新的代码)出现错误:'System.Data.Objects.ObjectQuery System.Data.Objects.ObjectQuery.Include (string)' 返回类型错误
  • @jop 已更新,构建一个新的 Action&lt;string&gt; 委托,调用 Cars.Include。或者,您的自定义 Include 方法可以接受 Func&lt;string, whatever type Cars.Include() returns&gt;
  • 约定是泛型变量应该有名为 arg 的参数 T,而不是参数。
【解决方案2】:

您正在寻找Action&lt;T&gt;,它带有一个参数。

【讨论】:

  • 您可能需要添加第二个T
  • 这个想法是将每个包含传递给方法 _context.Cars.Include()
【解决方案3】:

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

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

【讨论】:

  • 我喜欢这个,因为我有一个实用程序类已经在许多地方使用,但不接受Action&lt;T&gt; - 这让我仍然可以不加修改地使用它。
  • 这应该是公认的答案,但很简单。
  • 这是我使用的,带有一个 BlockingCollection 的 Action(s) 来模拟我使用 C++/Qt(信号/插槽机制)所拥有的东西
猜你喜欢
  • 1970-01-01
  • 2016-08-31
  • 1970-01-01
  • 1970-01-01
  • 2011-03-10
  • 2020-03-30
  • 2010-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多