How to pass parameter to Action?

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 that

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

The idea is that each of them includes a method.

+48
c # action
Feb 11 2018-11-11T00:
source share
3 answers

If you know which parameter you want to pass, take an Action<T> for this type. Example:

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

If you want this parameter to be passed to your method, run the general method:

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

And caller code:

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



Update Your code should look like this:

 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); } 
+58
Feb 11 2018-11-11T00:
source share

You are looking for an Action<T> that accepts a parameter.

+8
Feb 11 '11 at 4:05
source share

Dirty trick. You can also use a lambda expression to pass any code you want, including a call with parameters.

 this.Include(includes, () => { _context.Cars.Include(<parameters>); }); 
+3
Nov 25 '14 at 8:05
source share



All Articles