方法中的方法 [英] Method Within A Method

查看:16
本文介绍了方法中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a C# library with some reusable code and was trying to create a method inside a method. I have a method like this:

public static void Method1()
{
   // Code
}

我想做的是:

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

然后我可以选择Method1.Method2Method1.Method3.显然编译器对此并不满意,非常感谢任何帮助.谢谢.

Then I could choose either Method1.Method2 or Method1.Method3. Obviously the compiler isn't happy about this, any help is much appreciated. Thanks.

推荐答案

这个答案是在 C# 7 出来之前写的.使用 C# 7,您可以编写本地方法.

This answer was written before C# 7 came out. With C# 7 you can write local methods.

不,你不能那样做.您可以创建一个嵌套类:

No, you can't do that. You could create a nested class:

public class ContainingClass
{
    public static class NestedClass
    {
        public static void Method2()
        {
        } 

        public static void Method3()
        {
        }
    }
}

然后你会调用:

ContainingClass.NestedClass.Method2();

ContainingClass.NestedClass.Method3();

不会推荐这个.通常使用公共嵌套类型是个坏主意.

I wouldn't recommend this though. Usually it's a bad idea to have public nested types.

你能告诉我们更多关于你想要实现的目标吗?很可能有更好的方法.

Can you tell us more about what you're trying to achieve? There may well be a better approach.

这篇关于方法中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆