如何指定方法作为我方法的参数?

时间:2014-03-09 22:36:02

标签: c# methods

C#的新手,如何创建一个接受方法作为其参数之一的方法?

听起来很奇怪,但我希望它能在c#中得到支持。

我试过的:

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

这是我想传递的方法:

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

3 个答案:

答案 0 :(得分:7)

“将一个方法放在一个值中”(你可以用C#做​​很多事情,比如把它作为一个参数传递给另一个方法)被称为创建一个delegate 到那种方法。

委托具有直接对应于其指向的方法的签名的类型(即其参数的数量和类型以及返回值)。 C#为没有返回值(Action及其兄弟姐妹)的委托以及那些(Func及其兄弟姐妹)的代表提供现成的类型。

在您的情况下,Calculate的签名与Func<int, Condition, int>类型匹配,因此您可以写

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

并像

一样使用它
CalculateRepairedCars(i, Calculate);

答案 1 :(得分:3)

有多种方法。我以前用过Action来做这件事。

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
}

如果作为参数传递的方法本身具有参数(例如YetAnotherMethod(int param1)),则使用Action<T>传递它:

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

就我而言,我不必从作为参数传递的方法返回值。如果必须返回值,请使用Func及其相关的重载。


刚刚看到您使用您正在调用的方法更新了代码。

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

要返回值,您需要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
}

然后调用它类似于之前:

CalculateRepairedCars(100, Calculate);

答案 2 :(得分:1)

c#方法类型称为委托。你声明它,分配一个方法,然后你可以用它做很多事情,包括将它作为参数传递。抬头看!注意:代理类型安全,因为必须与他们指向的方法共享签名