我正在创建一个包含一些可重用代码的 C# 库,并试图在一个方法中创建一个方法。我有这样的方法:
public static void Method1()
{
// Code
}
我想做的是:
public static void Method1()
{
public static void Method2()
{
}
public static void Method3()
{
}
}
然后我可以选择 Method1.Method2
或 Method1.Method3
。显然编译器对此不满意,非常感谢任何帮助。谢谢。
最佳答案
如果嵌套方法是指只能在该方法内调用的方法(如在 Delphi 中),则可以使用委托(delegate)。
public static void Method1()
{
var method2 = new Action(() => { /* action body */ } );
var method3 = new Action(() => { /* action body */ } );
//call them like normal methods
method2();
method3();
//if you want an argument
var actionWithArgument = new Action<int>(i => { Console.WriteLine(i); });
actionWithArgument(5);
//if you want to return something
var function = new Func<int, int>(i => { return i++; });
int test = function(6);
}
关于c# - 方法中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8135050/