如何在Action中传递参数?

时间:2022-04-05 22:55:17
private void Include(IList<string> includes, Action action)
{
    if (includes != null)
    {
        foreach (var include in includes)
            action(<add include here>);
    }
}

I want to call it like that

我想这样称呼它

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

The idea is pass each include to the method.

这个想法是将每个include传递给方法。

3 个解决方案

#1


66  

If you know what parameter you want to pass, take a Action<T> for the type. Example:

如果您知道要传递的参数,请为该类型执行Action 。例:

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

If you want the parameter to be passed to your method, make the method generic:

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

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

And the caller code:

和来电者代码:

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

Update. Your code should look like:

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

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

#2


9  

You're looking for Action<T>, which takes a parameter.

你正在寻找Action ,它带有一个参数。

#3


5  

Dirty trick: You could as well use lambda expression to pass any code you want including the call with parameters.

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

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

#1


66  

If you know what parameter you want to pass, take a Action<T> for the type. Example:

如果您知道要传递的参数,请为该类型执行Action 。例:

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

If you want the parameter to be passed to your method, make the method generic:

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

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

And the caller code:

和来电者代码:

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

Update. Your code should look like:

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

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

#2


9  

You're looking for Action<T>, which takes a parameter.

你正在寻找Action ,它带有一个参数。

#3


5  

Dirty trick: You could as well use lambda expression to pass any code you want including the call with parameters.

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

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