在C#中写代码分隔符的更优雅方法?

13

在C#中,当我有不同的代码部分,比如常量、API函数、辅助函数等,我想将它们分开。我通常会使用类似于这样的方式:

public class Foo {

      //================== Constants ==================
      private const string VIP = "Cob H.";
      private const int IMPORTANT_NUMBER = 23; 

      //================== API Functions ==================
      [WebMethod(MessageName = "SomeInformation")]
      public string SomeInformation() {
            return VIP + " is dead.";
      }

      //================== Inner Classes ==================
      private class IrrelevantClass {
            public string Name { get; set; }
            public string City { get; set; }
      }
}

有没有一种优雅的方法来划分它们,而不是使用一堆丑陋的注释?就像在 Objective-C 中你可以使用

#pragma mark - Inner Classes

我查看了C#中编译指示列表中的所有关键字,但没有一个看起来很有前途。


6
#region Constants .... #endregion 的翻译是:#region 常量 .... #endregion - Tim Schmelter
2
哇,我真的很惊讶你们在SO上回答问题的速度,当我回来5分钟后看到所有的答案和投票时,我有一种幻觉,好像我已经睡了一晚上,然后才刚刚醒来。 - RomanKousta
4个回答

34

C#有区域,其功能类似。要使用区域,您的代码应该像这样:

public class Foo {

      #region Constants
      private const string VIP = "Cob H.";
      private const int IMPORTANT_NUMBER = 23; 
      #endregion

      #region API Functions
      [WebMethod(MessageName = "SomeInformation")]
      public string SomeInformation() {
            return VIP + " is dead.";
      }
      #endregion

      #region Inner Classes 
      private class IrrelevantClass {
            public string Name { get; set; }
            public string City { get; set; }
      }
      #endregion
}

如果您正在使用Visual Studio,C#编辑器允许您折叠区域,使得浏览大型源文件更加容易。


7
我唯一要补充的是,在 #endregion 指令中应该加上该区域的名称(例如 #endregion Constants)。这样,如果该区域有点长而你在底部,你也知道自己在哪里。 - Craig W.

6

您可以使用#regions

#region允许您指定一个代码块,在使用Visual Studio Code编辑器的大纲功能时,您可以展开或折叠该代码块。

public class Foo
{

    #region Constants
    private const string VIP = "Cob H.";
    private const int IMPORTANT_NUMBER = 23;
    #endregion

    //......rest of the code

}

3
你可以使用 #regions,但是它有一些缺点,比如人们倾向于在其中隐藏肮脏的代码或隐藏一些长而痛苦的方法。
我也可以接受你的方法,但基本上编写代码应该不需要隐藏在#regions下。
如果你将其编写为可读格式,那么根本不需要分隔符...

我强烈不同意你最后的评论。区域不是(也不应该是)关于可读性,而是关于组织代码并在不显示文件的其余部分的情况下处理您感兴趣的区域。 - Franz B.

1
我尝试使用#region,但我不喜欢使用Ctrl + M,O(折叠到定义热键)会折叠区域,以至于我无法轻松查看每个功能/成员在其中的情况。我尝试使用块注释,但那些也会折叠。

我想出了自己的高可见性、多行分隔符,使用Collapse to Definitions时不会折叠。也许其他人会发现这个想法有用:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接