一般来说,你正在寻找一个Action
或Func
。这是一个封装可执行代码的类型:
public int YourCommonMethod(int parameter, Func<int, int> calculate)
{
// some common code
if(calculationNeeded)
{
// some common code
result = calculate(parameter);
}
// more common code
}
然后,您可以用两种不同的计算方法称之为:
int result = YourCommonMethod(5, i => i + 17);
OR
int result = YourCommonMethod(5, i => i/48);
对于只是一个动作,你需要更少的:
public int YourCommonMethod(int parameter, Action<int> doWork)
{
// some common code
if(calculationNeeded)
{
// some common code
doWork(parameter);
}
// more common code
}
你可以这样调用:
int result = YourCommonMethod(5, Console.WriteLine);
OR
int result = YourCommonMethod(5, i => Console.WriteLine("Some string including {0}", i));
是2号线和一号线的东西,你可以从函数外通? – nvoigt
不,它必须在 – AnasB