简体   繁体   中英

How can I specify a method as a parameter of my method?

New to C#, how can I create a method that will accept a method as one of its parameters?

Sounds little weird but I hope that it will be supported in c#.

That what I tried:

public void CalculateRepairedCars(int total, /*here I want to pass a method..*/)
{
    ...
}

This is the method which I would like to pass:

public int Calculate{int totalCars, Condition condition}
{
...
}

"Putting a method inside a value" (which you can then do many things with, such as passing as an argument to another method) in C# is called creating a delegate to that method.

A delegate has a type that directly corresponds to the signature of the method it points to (ie the number and types of its arguments and the return value). C# offers ready-made types for delegates that do not return a value ( Action and its siblings) and for those that do ( Func and its siblings).

In your case, the signature of Calculate matches the type Func<int, Condition, int> so you would write

public void CalculateRepairedCars(int total, Func<int, Condition, int> calc)
{
    // when you want to invoke the delegate:
    int result = calc(someCondition, someInteger);
}

and use it like

CalculateRepairedCars(i, Calculate);

There are multiple ways. I've used an Action to do it before.

private void SomeMethod()
{
    CalculateRepairedCars(100, YetAnotherMethod);
}

public void CalculateRepairedCars(int total, Action action)
{
    action.Invoke();  // execute the method, in this case "YetAnotherMethod"
}

public void YetAnotherMethod()
{
    // do stuff
}

If the method being passed as a parameter has parameters itself, (such as YetAnotherMethod(int param1) ), you'd pass it in using Action<T> :

CalculateRepairedCars(100, () => YetAnotherMethod(0));

In my case, I didn't have to return a value from the method passed as a parameter. If you have to return a value, use Func and its related overloads.


Just saw you updated your code with the method you're calling.

public int Calculate(int totalCars, Condition condition)
{
    ...
}

To return a value, you'd need Func :

public void CalculateRepairedCars(int total, Func<int, string, int> func)
{
    var result
        = func.Invoke(total, someCondition);  // where's "condition" coming from?

    // do something with result since you're not returning it from this method
}

Then call it similar to before:

CalculateRepairedCars(100, Calculate);

The c# method type is called delegate . You declare it, assign a method and then you can do many things with it including passing it as a parameter. Look it up! Note: delegates are sort of type safe in that the must share the signature with the methods they point to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM