C#代码规范

C# 编码规范 先猜个谜再看吧 两只蚂蚁一起慢慢的爬着,忽然一只蚂蚁发现一个大大的梨子。(猜两个国家的名) 谜底在文章未   Technotes, HowTo Series C# Coding Style Guide Version 0.3by Mike Krüger icsharpcode.net About the C# Coding Style Guide File Organization Inden 阅读详情

Technotes, HowTo Series

C# Coding Style Guide

Version 0.3
by Mike Krüger icsharpcode.net

  1. About the C# Coding Style Guide
  2. File Organization
  3. Indentation
  4. Comments
  5. Declarations
  6. Statements
  7. White Space
  8. Naming Conventions
  9. Programming Practices
  10. Code Examples

1. About the C# Coding Style Guide

This document may be read as a guide to writing robust and reliable programs. It focuses on programs written in C#, but many of the rules and principles are useful even if you write in another programming language.

2. File Organization

2.1 C# Sourcefiles

Keep your classes/files short, don't exceed 2000 LOC, divide your code up, make structures clearer. Put every class in a separate file and name the file like the class name (with .cs as extension of course). This convention makes things much easier.

2.2 Directory Layout

Create a directory for every namespace. (For MyProject.TestSuite.TestTier use MyProject/TestSuite/TestTier as the path, do not use the namespace name with dots.) This makes it easier to map namespaces to the directory layout.

3. Indentation

3.1 Wrapping Lines

When an expression will not fit on a single line, break it up according to these general principles:

  • Break after a comma.
  • Break after an operator.
  • Prefer higher-level breaks to lower-level breaks.
  • Align the new line with the beginning of the expression at the same level on the previous line

    Example of breaking up method calls:

    longMethodCall(expr1, expr2,
    ???????????????expr3, expr4, expr5);

    Examples of breaking an arithmetic expression:

    PREFER:

    var = a * b / (c - g + f) +
    ??????4 * z;

    BAD STYLE – AVOID:

    var = a * b / (c - g +
    ??????f) + 4 * z;

    The first is preferred, since the break occurs outside the paranthesized expression (higher level rule). Note that you indent with tabs to the indentation level and then with spaces to the breaking position in our example this would be:

     > var = a * b / (c - g + f) + > ......4 * z;  

    Where '>' are tab chars and '.' are spaces. (the spaces after the tab char are the indent with of the tab). A good coding practice is to make the tab and space chars visible in the editor which is used.

    3.2 White Spaces

    An indentation standard using spaces never was achieved. Some people like 2 spaces, some prefer 4 and others die for 8, or even more spaces. Better use tabs. Tab characters have some advantages:

  • Everyone can set their own preferred indentation level
  • It is only 1 character and not 2, 4, 8 … therefore it will reduce typing (even with smartindenting you have to set the indentation manually sometimes, or take it back or whatever)
  • If you want to increase the indentation (or decrease), mark one block and increase the indent level with Tab with Shift-Tab you decrease the indentation. This is true for almost any texteditor.

    Here, we define the Tab as the standard indentation character.

    Don't use spaces for indentation - use tabs!

    4. Comments

    4.1 Block Comments

    Block comments should usually be avoided. For descriptions use of the /// comments to give C# standard descriptions is recommended. When you wish to use block comments you should use the following style :

     /* Line 1 * Line 2 * Line 3 */  

    As this will set off the block visually from code for the (human) reader. Alternatively you might use this oldfashioned C style for single line comments, even though it is not recommended. In case you use this style, a line break should follow the comment, as it is hard to see code preceeded by comments in the same line:

     /* blah blah blah */ 

    Block comments may be useful in rare cases, refer to the TechNote 'The fine Art of Commenting' for an example. Generally block comments are useful for comment out large sections of code.

    4.2 Single Line Comments

    You should use the // comment style to "comment out" code (SharpDevelop has a key for it, Alt+/) . It may be used for commenting sections of code too.

    Single line comments must be indented to the indent level when they are used for code documentation. Commented out code should be commented out in the first line to enhance the visibility of commented out code.

    A rule of thumb says that generally, the length of a comment should not exceed the length of the code explained by too much, as this is an indication of too complicated, potentially buggy, code.

    4.3 Documentation Comments

    In the .net framework, Microsoft has introduced a documentation generation system based on XML comments. These comments are formally single line C# comments containing XML tags. They follow this pattern for single line comments:

     ///  /// This class... ///  

    Multiline XML comments follow this pattern:

     /// 
             
               /// This exception gets thrown as soon as a /// Bogus flag gets set. /// 
              

    All lines must be preceded by three slashes to be accepted as XML comment lines. Tags fall into two categories:

  • Documentation items
  • Formatting/ Referencing

    The first category contains tags like

    , or . These represent items that represent the elements of a program's API which must be documented for the program to be useful to other programmers. These tags usually have attributes such as name or cref as demonstrated in the multiline example above. These attributes are checked by the compiler, so they should be valid. The latter category governs the layout of the documentation, using tags such as , or .
    Documentation can then be generated using the 'documentation' item in the #develop 'build' menu. The documentation generated is in HTMLHelp format.
    For a fuller explanation of XML comments see the Microsoft .net framework SDK documentation. For information on commenting best practice and further issues related to commenting, see the TechNote 'The fine Art of Commenting'.

    5. Declarations

    5.1 Number of Declarations per Line

    One declaration per line is recommended since it encourages commenting1. In other words,

     int level; // indentation level int size; // size of table 

    Do not put more than one variable or variables of different types on the same line when declaring them. Example:

     int a, b; //What is 'a'? What does 'b' stand for? 

    The above example also demonstrates the drawbacks of non-obvious variable names. Be clear when naming variables.

    5.2 Initialization

    Try to initialize local variables as soon as they are declared. For example:
     string name = myObject.Name; 
    or
     int val = time.Hours; 
    Note: If you initialize a dialog try to use the using statement:
     using (OpenFileDialog openFileDialog = new OpenFileDialog()) { ... } 

    5.3 Class and Interface Declarations

    When coding C# classes and interfaces, the following formatting rules should be followed:

    • No space between a method name and the parenthesis " (" starting its parameter list.
    • The opening brace "{" appears in the next line after the declaration statement
    • The closing brace "}" starts a line by itself indented to match its corresponding opening brace.

      For example:

       Class MySample : MyClass, IMyInterface { int myInt; public MySample(int myInt) { this.myInt = myInt ; } void Inc() { ++myInt; } void EmptyMethod() { } } 

      For a brace placement example look at section 10.1.

      6. Statements

      6.1 Simple Statements

      Each line should contain only one statement.

      6.2 Return Statements

      A return statement should not use outer most parentheses. Don't use :

       return (n * (n + 1) / 2); use : return n * (n + 1) / 2; 

      6.3 If, if-else, if else-if else Statements

      if, if-else and if else-if else statements should look like this:

       if (condition) { DoSomething(); ... } if (condition) { DoSomething(); ... } else { DoSomethingOther(); ... } if (condition) { DoSomething(); ... } else if (condition) { DoSomethingOther(); ... } else { DoSomethingOtherAgain(); ... } 

      6.4 For / Foreach Statements

      A for statement shoud have following form :
       for (int i = 0; i < 5; ++i) { ... } 
      or single lined (consider using a while statement instead) :
       for (initialization; condition; update) ; A foreach should look like : foreach (int i in IntList) { ... } 
      Note: Generally use brackets even if there is only one statement in the loop.

      6.5 While/do-while Statements

      A while statement should be written as follows:
       while (condition) { ... } 

      An empty while should have the following form:

       while (condition) ; 
      A do-while statement should have the following form:
       do { ... } while (condition); 

      6.6 Switch Statements

      A switch statement should be of following form:
       switch (condition) { case A: ... break; case B: ... break; default: ... break; } 

      6.7 Try-catch Statements

      A try-catch statement should follow this form:

       try { ... } catch (Exception) {} or try { ... } catch (Exception e) { ... } or try { ... } catch (Exception e) { ... } finally { ... } 

      7. White Space

      7.1 Blank Lines

      Blank lines improve readability. They set off blocks of code which are in themselves logically related. Two blank lines should always be used between:

    • Logical sections of a source file
    • Class and interface definitions (try one class/interface per file to prevent this case) One blank line should always be used between:
    • Methods
    • Properties
    • Local variables in a method and its first statement
    • Logical sections inside a method to improve readability Note that blank lines must be indented as they would contain a statement this makes insertion in these lines much easier.

      7.2 Inter-term spacing

      There should be a single space after a comma or a semicolon, for example:
       TestMethod(a, b, c); don't use : TestMethod(a,b,c) 
      or
       TestMethod( a, b, c ); Single spaces surround operators (except unary operators like increment or logical not), example: a = b; // don't use a=b; for (int i = 0; i < 10; ++i) // don't use for (int i=0; i<10; ++i) // or // for(int i=0;i<10;++i) 

      7.3 Table like formatting

      A logical block of lines should be formatted as a table:

       string name = "Mr. Ed"; int myValue = 5; Test aTest = Test.TestYou; 

      Use spaces for the table like formatting and not tabs because the table formatting may look strange in special tab intent levels.

      8. Naming Conventions

      8.1 Capitalization Styles

      8.1.1 Pascal Casing

      This convention capitalizes the first character of each word (as in TestCounter).

      8.1.2 Camel Casing

      This convention capitalizes the first character of each word except the first one. E.g. testCounter.

      8.1.3 Upper case

      Only use all upper case for identifiers if it consists of an abbreviation which is one or two characters long, identifiers of three or more characters should use Pascal Casing instead. For Example:

       public class Math { public const PI = ... public const E = ... public const feigenBaumNumber = ... } 

      8.2. Naming Guidelines

      Generally the use of underscore characters inside names and naming according to the guidelines for Hungarian notation are considered bad practice.

      Hungarian notation is a defined set of pre and postfixes which are applied to names to reflect the type of the variable. This style of naming was widely used in early Windows programming, but now is obsolete or at least should be considered deprecated. Using Hungarian notation is not allowed if you follow this guide.

      And remember: a good variable name describes the semantic not the type.

      An exception to this rule is GUI code. All fields and variable names that contain GUI elements like button should be postfixed with their type name without abbreviations. For example:

       System.Windows.Forms.Button cancelButton; System.Windows.Forms.TextBox nameTextBox; 

      8.2.1 Class Naming Guidelines

    • Class names must be nouns or noun phrases.
    • UsePascal Casing see 8.1.1
    • Do not use any class prefix

      8.2.2 Interface Naming Guidelines

    • Name interfaces with nouns or noun phrases or adjectives describing behavior. (Example IComponent or IEnumberable)
    • Use Pascal Casing (see 8.1.1)
    • Use I as prefix for the name, it is followed by a capital letter (first char of the interface name)

      8.2.3 Enum Naming Guidelines

    • Use Pascal Casing for enum value names and enum type names
    • Don’t prefix (or suffix) a enum type or enum values
    • Use singular names for enums
    • Use plural name for bit fields.

      8.2.4 ReadOnly and Const Field Names

    • Name static fields with nouns, noun phrases or abbreviations for nouns
    • Use Pascal Casing (see 8.1.1)

      8.2.5 Parameter/non const field Names

    • Do use descriptive names, which should be enough to determine the variable meaning and it’s type. But prefer a name that’s based on the parameter’s meaning.
    • Use Camel Casing (see 8.1.2)

      8.2.6 Variable Names

    • Counting variables are preferably called i, j, k, l, m, n when used in 'trivial' counting loops. (see 10.2 for an example on more intelligent naming for global counters etc.)
    • Use Camel Casing (see 8.1.2)

      8.2.7 Method Names

    • Name methods with verbs or verb phrases.
    • Use Pascal Casing (see 8.1.2)

      8.2.8 Property Names

    • Name properties using nouns or noun phrases
    • Use Pascal Casing (see 8.1.2)
    • Consider naming a property with the same name as it’s type

      8.2.9 Event Names

    • Name event handlers with the EventHandler suffix.
    • Use two parameters named sender and e
    • Use Pascal Casing (see 8.1.1)
    • Name event argument classes with the EventArgs suffix.
    • Name event names that have a concept of pre and post using the present and past tense.
    • Consider naming events using a verb.

      8.2.10 Capitalization summary

      TypeCaseNotes
      Class / StructPascal Casing?
      InterfacePascal CasingStarts with I
      Enum valuesPascal Casing?
      Enum typePascal Casing?
      EventsPascal Casing?
      Exception classPascal CasingEnd with Exception
      public FieldsPascal Casing?
      MethodsPascal Casing?
      NamespacePascal Casing?
      PropertyPascal Casing?
      Protected/private FieldsCamel Casing?
      ParametersCamel Casing?

      9. Programming Practices

      9.1 Visibility

      Do not make any instance or class variable public, make them private. For private members prefer not using “private” as modifier just do write nothing. Private is the default case and every C# programmer should be aware of it.

      Use properties instead. You may use public static fields (or const) as an exception to this rule, but it should not be the rule.

      9.2 No 'magic' Numbers

      Don’t use magic numbers, i.e. place constant numerical values directly into the source code. Replacing these later on in case of changes (say, your application can now handle 3540 users instead of the 427 hardcoded into your code in 50 lines scattered troughout your 25000 LOC) is error-prone and unproductive. Instead declare a const variable which contains the number :

       public class MyMath { public const double PI = 3.14159... } 

      10. Code Examples

      10.1 Brace placement example

       namespace ShowMeTheBracket { public enum Test { TestMe, TestYou } public class TestMeClass { Test test; public Test Test { get { return test; } set { test = value; } } void DoSomething() { if (test == Test.TestMe) { //...stuff gets done } else { //...other stuff gets done } } } } 
      Brackets should begin on a new line only after:
    • Namespace declarations (note that this isnew in version 0.3 and was different in 0.2)
    • Class/ Interface / Struct declarations
    • Method Declarations

      10.2 Variable naming example

      instead of :
       for (int i = 1; i < num; ++i) { meetsCriteria[i] = true; } for (int i = 2; i < num / 2; ++i) { int j = i + i; while (j <= num) { meetsCriteria[j] = false; j += i; } } for (int i = 0; i < num; ++i) { if (meetsCriteria[i]) { Console.WriteLine(i + " meets criteria"); } } try intelligent naming : for (int primeCandidate = 1; primeCandidate < num; ++primeCandidate) { isPrime[primeCandidate] = true; } for (int factor = 2; factor < num / 2; ++factor) { int factorableNumber = factor + factor; while (factorableNumber <= num) { isPrime[factorableNumber] = false; factorableNumber += factor; } } for (int primeCandidate = 0; primeCandidate < num; ++primeCandidate) { if (isPrime[primeCandidate]) { Console.WriteLine(primeCandidate + " is prime."); } } 

      Note: Indexer variables generally should be called i, j, k etc. But in cases like this, it may make sense to reconsider this rule. In general, when the same counters or indexers are reused, give them meaningful names.

遵循C#代码规范提升代码质量 函数定义和调用时的空格使用也需遵循一致的规则,以便保持代码的整洁与一致性:在函数名和开括号之间不需要空格,而参数列表内部的元素之间则需要适当空格。例如:csharp函数调用时,括号内部的元素同样应遵循空格规则,确保调用的清晰度。例如:csharpNUnit是一个免费的单元测试框架,它兼容JUnit,并且是第一个专门为.NET平台设计的测试框架。NUnit提供了丰富的断言方法,并支持测试属性、测试初始化与清理等高级功能。[Test] 阅读详情

相关推荐

c#coding style

c#coding style, 规范格式,养成良好编程习惯。

Writing custom visualizers for Visual Studio 2005

Writing custom visualizers for Visual Studio 2005

witton的专栏 1018

C# Coding Style Guide

C# Coding Style Guide

C#编码规范(C# Coding Style)

以下是微软 .NET core项目使用的编码风格,文中给了一个开源软件可以格式化你的C#项目文件,以保持编码风格的统一。有需要的可以下载研究一下~

青烟绕指柔丶 1023

Coding Style Guide

Coding Style Guide,非常好的一本书

MobaXterm远程连接频繁掉线?3个SSH保活设置让你告别断连烦恼

本文针对MobaXterm远程连接频繁掉线问题,提供了3个SSH保活设置方案。从基础的SSH心跳机制到进阶的会话超时调整,再到TCP层保活与代理优化,全方位解决断连烦恼。特别适合需要稳定远程连接的开发者和运维人员,有效提升工作效率。

weixin_29250573的博客 500

JavaTutorial之Annotation

作用: Information for the compiler (给编译器提供信息):编译器可以使用注释来检测错误或抑制警告。 Compile-time and deployment-time processing(编译和部署阶段的一些处理)软件工具可以处理注释信息以生成代码、XML文件等。 Runtime processing(运行时的一些处理)有些注释可以运行的时候被检查。 每个注释通常出现在自己的行中。 Declaring an Annotation Type(声明批注类型) Annotatio

qq_39199850的博客 256

高效敏感词检测API平台对比与选型指南

本文为开发者提供了高效敏感词检测API平台的选型指南。文章对比了专业API平台、头部云厂商、新兴AI服务商及开源方案,从检测能力、集成易用性、成本、稳定性及扩展性五大维度进行分析,并给出实战选型建议,帮助团队根据业务场景快速选择最合适的敏感词检测服务。

weixin_29325955的博客 352

【C#语言】代码规范

在 C# 的标识符命名中,主要遵循两种命名风格:Pascal 命名法和 Camel 命名法。Pascal 命名法要求每个单词的首字母都大写,例如 “CustomerName”“OrderTotal”。这种命名法常用于类名、方法名、属性名、命名空间等,能够清晰地标识出不同的代码元素,增强代码的可读性和专业性。

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 1243

VLM,VLA,VLN的区别与联系

VLM 提供了理解世界的“眼睛和大脑”,VLN 赋予了这个智能体在空间中“移动的双腿”,而 VLA 则进一步赋予了它“灵巧的双手”来改变世界。三者共同构成了一个完整具身智能体的核心能力模块。

l0409044222的博客 1333

快速上手springboot+vue的前后端分离项目

使用webStorm新建项目后,把 .lock文件删除后项目运行才不报错,配置文件 vue.config.js 中加入 lintOnSave: false 关闭eslint语法检测。在多层嵌套的父子组件之间传递状态已经十分麻烦,而Vue更是没有为兄弟组件提供直接共享数据的办法。基于这个问题,许多框架提供了解决方案——使用全局的状态管理器,将所有分散的共享数据交由状态管理器保管,Vue也不例外。其中一种解决CORS 的方法, 在springboot项目中跨域的方法或类加上@CrossOrigin注解。

m0_61950264的博客 1913

C#代码规范检查工具

C#代码规范检查工具是现代软件开发流程中不可或缺的重要组成部分。这些工具通过静态代码分析技术,能够自动检测源代码中不符合编程规范、潜在错误以及不良实践的问题。在团队协作开发环境中,统一的代码风格和高质量标准对项目的可维护性和可扩展性至关重要。C#作为微软推出的面向对象编程语言,在企业级应用开发领域占据主导地位,因此针对C#语言的代码规范检查工具也形成了丰富的生态体系。这些工具不仅能够帮助开发人员早期发现代码缺陷,还能促进团队形成一致的编码风格,显著提高代码质量和开发效率。

kongxiangjian00的博客 1282

100天精通Python(基础篇)——第4天:数据类型全解析_从基础到转换

数据类型全解析_从基础到转换

努力让自己发光,对的人才能迎着光而来 11万+

C#编程代码规范与风格

最后,确保所有跨平台的代码都使用相同的命名规范和编译器选项,这有助于减少平台之间的兼容性问题。此外,使用C#中的`Reflection`库可以帮助我获取C#代码的C实现,并且支持跨平台的编译器选项。他们想要一篇高度原创的文章,长度在1500到3000字之间,每个段落用h2标签,还有4个副标题分别对应主标题中的四个关键词,也就是代码规范、代码风格、C#语言和Web开发。此外,代码风格的统一也是为了确保代码的可读性和维护性,特别是在大型项目中,文档和测试用例的编写往往占据了相当大的篇幅。

a5155114的博客 1648

GEE:基于自定义的年度时序数据集进行LandTrendr变化检测

本文介绍了使用年度时序数据进行LandTrendr变化检测的方法,包括核心函数调用、参数设置和结果可视化。通过筛选参数(年份、变化幅度和持续时间)对结果进行过滤,输出变化年份、变化幅度和持续时间。代码提供了完整的处理流程,包括数据输入、LandTrendr算法运行、结果筛选与可视化,并支持结果导出。适用于基于Google Earth Engine平台的地表变化检测分析。

养乐多的博客 757

3D Slicer学习记录(4)-PLUSapp连接双目相机Intel Realsense

plusapp是基于openIGTLink协议的免费的开源库和应用程序API接口,用于数据采集、预处理、校准和实时流成像、位置跟踪和其他传感器数据。这里以intel realsense双目相机为例详细的演示整个图像流导入到3D Slicer的流程。

weixin_39090239的博客 1354

C#项目代码规范

目的   1.方便代码的交流和维护。   2.不影响编码的效率,不与大众习惯冲突。   3.使代码更美观、阅读更方便。   4.使代码的逻辑更清晰、更易于理解。 在C#中通常使用的两种编码方式如下   Camel(驼峰式): 大小写形式-除了第一个单词,所有单词第一个字母大写,其他字母小写。  Pascal(帕斯卡): 大小写形式-所有单词第一个字母大写,其他字母小写。 C...

ddry47579的博客 260

Python图像处理之光斑分析

光斑是工程中经常出现的图像数据,其特点是目标明确,分布清晰。对光斑图像的分析,主要包括质心定位、目标截取以及半径拟合等。

微小冷的学习笔记 2865

C#代码规范(简版)

C#项目代码规范 目的   1.方便代码的交流和维护。   2.不影响编码的效率,不与大众习惯冲突。   3.使代码更美观、阅读更方便。   4.使代码的逻辑更清晰、更易于理解。 在C#中通常使用的两种编码方式如下   Camel(驼峰式): 大小写形式-除了第一个单词,所有单词第一个字母大写,其他字母小写。  Pascal(帕斯卡): 大小写形式-所有单词第一个字...

weixin_30835933的博客 85

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

好代码是管出来的——C#的代码规范

代码是软件开发过程的产物,代码的作用是通过编译器编译后运行,达到预期的效果(功能、稳定性、安全性等等),而另外一个重要作用是给人阅读。对于机器来说只要代码正确就能够正确的...

dotNET跨平台 517

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

下一篇: 般若波罗蜜多心经
newdan
博客等级 码龄23年 4粉丝 26原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址