c# - 方法中的方法

标签 c# methods

我正在创建一个包含一些可重用代码的 C# 库,并试图在一个方法中创建一个方法。我有这样的方法:

public static void Method1()
{
   // Code
}

我想做的是:

public static void Method1()
{
   public static void Method2()
   {
   }
   public static void Method3()
   {
   }
}

然后我可以选择 Method1.Method2Method1.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/

相关文章:

c# - 如何在VB6和C#之间发送/接收Windows消息?

c# - 如何创建一个只读 token 来验证某些值?

php - 如何测试属性中是否存在方法?

javascript - includes() 不适用于所有浏览器

c# - 在 onStart() 方法中停止 Windows 服务

c# - 带网络流的充气城堡

c# - 如何修复异常无法加载 DLL 'gdiplus.dll' : The specified module could not be found

java - 如何将方法中用户输入的所有输出相加?

ruby - 如何使 Ruby 方法传递输出参数(更改引用参数的值)?

actionscript-3 - ActionScript - 重写方法而不匹配签名?