c# - 布局 C# 类的最佳方式是什么?

标签 c# coding-style

<分区>

是否有一种标准的 C# 文件布局方式?比如,字段,然后是属性,然后是构造函数,等等?

这是我通常做的,但我想知道是否有标准方法?

  1. 嵌套类或枚举
  2. 领域
  3. 属性
  4. 事件
  5. 构造器
  6. 公共(public)方法
  7. 私有(private)方法

人们是将他们的字段组合在一起,还是将它们与属性放在一起?或者人们不担心订单? Visual Studio 似乎很难做到。

编辑:将有关 ReSharper 的其他部分移至此处:Make Resharper respect your preference for code order.

最佳答案

我倾向于使用 Microsoft StyleCop ,根据规则设置顺序 SA1201 :

Cause An element within a C# code file is out of order in relation to the other elements in the code.

Rule Description A violation of this rule occurs when the code elements within a file do not follow a standard ordering scheme.

To comply with this rule, elements at the file root level or within a namespace must be positioned in the following order:

  • Extern Alias Directives
  • Using Directives
  • Namespaces
  • Delegates
  • Enums
  • Interfaces
  • Structs
  • Classes

Within a class, struct, or interface, elements must be positioned in the following order:

  • Fields
  • Constructors
  • Finalizers (Destructors)
  • Delegates
  • Events
  • Enums
  • Interfaces
  • Properties
  • Indexers
  • Methods
  • Structs
  • Classes

Complying with a standard ordering scheme based on element type can increase the readability and maintainability of the file and encourage code reuse.

When implementing an interface, it is sometimes desirable to group all members of the interface next to one another. This will sometimes require violating this rule, if the interface contains elements of different types. This problem can be solved through the use of partial classes.

  1. Add the partial attribute to the class, if the class is not already partial.

  2. Add a second partial class with the same name. It is possible to place this in the same file, just below the original class, or within a second file.

  3. Move the interface inheritance and all members of the interface implementation to the second part of the class.

关于c# - 布局 C# 类的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/603758/

相关文章:

java - 是否需要将私有(private)嵌套类的内部声明为私有(private)?

java - 在函数中使用 for-each 循环更好,还是 while 循环和 “found” 变量更好?

ruby - 扩展方法不是 "the Ruby way"吗?

c# - EF 6.0 where 子句后的项目不正确

c# - 将批处理文件输出重定向到 winform 文本框问题

c# - WCF Web JSON 请求双斜线

java - 为什么在Java中使用4个空格作为缩进单位?

c# - 鼠标双击仅在右键单击时触发

c# - 为什么重新启动进程时不再收到 OutputDataReceived 事件?

android - Eclipse 无法识别 Android 布局构建器中的样式?