我如何在Action中传递一个参数?

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

这个想法是通过每个包括的方法。

如果你知道你想要传递什么参数,请为这个types使用一个Action<T> 。 例:

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

如果你想把这个parameter passing给你的方法,使这个方法是通用的:

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

您正在寻找带有参数的Action<T>

肮脏的把戏:你可以使用lambdaexpression式来传递任何代码,包括调用参数。

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