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>));
这个想法是将每个include传递给方法。
答案 0 :(得分:86)
如果您知道要传递的参数,请为该类型选择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);
}
答案 1 :(得分:10)
您正在寻找带有参数的Action<T>
。
答案 2 :(得分:6)
肮脏的技巧:您也可以使用lambda表达式传递您想要的任何代码,包括带参数的调用。
this.Include(includes, () =>
{
_context.Cars.Include(<parameters>);
});