Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a parameter in Action?

Tags:

c#

.net

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 like that

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

The idea is pass each include to the method.

like image 661
Jop Avatar asked Feb 11 '11 04:02

Jop


People also ask

How do you pass parameter values?

If you want the called method to change the value of the argument, you must pass it by reference, using the ref or out keyword. You may also use the in keyword to pass a value parameter by reference to avoid the copy while guaranteeing that the value will not be changed. For simplicity, the following examples use ref .

What are the ways to pass parameters to and from procedure?

Parameters can be passed to a method in following three ways : Value Parameters. Reference Parameters. Output Parameters.

How do you pass an action to a method?

Use Action Delegate to Pass a Method as a Parameter in C# We can also use the built-in delegate Action to pass a method as a parameter. The correct syntax to use this delegate is as follows. Copy public delegate void Action<in T>(T obj); The built-in delegate Action can have 16 parameters as input.

Can I pass this as parameter?

"Can I pass “this” as a parameter to another function in javascript" --- yes you can, it is an ordinary variable with a reference to current object.


1 Answers

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); } 
like image 143
The Scrum Meister Avatar answered Oct 09 '22 20:10

The Scrum Meister