How can I pass a parameter in Action?

后端 未结 3 859
别那么骄傲
别那么骄傲 2020-12-04 17:26
private void Include(IList includes, Action action)
{
    if (includes != null)
    {
        foreach (var include in includes)
            action(<         


        
相关标签:
3条回答
  • 2020-12-04 18:00

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

    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);
    }
    
    0 讨论(0)
  • 2020-12-04 18:00

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

    this.Include(includes, () =>
    {
        _context.Cars.Include(<parameters>);
    });
    
    0 讨论(0)
  • 2020-12-04 18:04

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

    0 讨论(0)
提交回复
热议问题