您当前的位置:首页 > 电脑百科 > 程序开发 > 语言 > C/C++/C#

C#编码标准和命名约定

时间:2020-08-24 16:41:30  来源:  作者:

Below are our C# coding standards, naming conventions, and best practices.
Use these in your own projects and/or adjust these to your own needs.



douse PascalCasing for class names and method names.

public class ClientActivity{    
  public void ClearStatistics()   
  {        //...   
}    
  public void CalculateStatistics()    {        //...   
  }
}

Why: consistent with the Microsoft's .NET Framework and easy to read.



douse camelCasing for local variables and method arguments.

public class UserLog
{   
  public void Add(LogEvent logEvent)  
  {      
  int itemCount = logEvent.Items.Count;      
    // ...    
                                                              
  }
}

Why: consistent with the Microsoft's .NET Framework and easy to read.



do notuse Hungarian notation or any other type identification in identifiers

// Correct
int counter;
string name; 
// Avoid
int iCounter;
string strName;

Why: consistent with the Microsoft's .NET Framework and Visual Studio IDE makes determining types very easy (via tooltips). In general you want to avoid type indicators in any identifier.



do notuse Screaming Caps for constants or readonly variables

    // Correct
    public static const string ShippingType = "DropShip";
     
    // Avoid
    public static const string SHIPPINGTYPE = "DropShip";

Why: consistent with the Microsoft's .NET Framework. Caps grap too much attention.



avoidusing Abbreviations. Exceptions: abbreviations commonly used as names, such as Id, Xml, Ftp, Uri

    // Correct
    UserGroup userGroup;
    Assignment employeeAssignment;
     
    // Avoid
    UserGroup usrGrp;
    Assignment empAssignment;
     
    // Exceptions
    CustomerId customerId;
    XmlDocument xmlDocument;
    FtpHelper ftpHelper;
    UriPart uriPart;

Why: consistent with the Microsoft's .NET Framework and prevents inconsistent abbreviations.



douse PascalCasing for abbreviations 3 characters or more (2 chars are both uppercase)

    htmlHelper htmlHelper;
    FtpTransfer ftpTransfer;
    UIControl uiControl;

Why: consistent with the Microsoft's .NET Framework. Caps would grap visually too much attention.



do notuse Underscores in identifiers. Exception: you can prefix private static variables
with an underscore.

    // Correct
    public DateTime clientAppointment;
    public TimeSpan timeLeft;
     
    // Avoid
    public DateTime client_Appointment;
    public TimeSpan time_Left;
     
    // Exception
    private DateTime _registrationDate;

Why: consistent with the Microsoft's .NET Framework and makes code more natural to read (without 'slur'). Also avoids underline stress (inability to see underline).



douse predefined type names instead of system type names like Int16, Single, UInt64, etc

    // Correct
    string firstName;
    int lastIndex;
    bool isSaved;
     
    // Avoid
    String firstName;
    Int32 lastIndex;
    Boolean isSaved;

Why: consistent with the Microsoft's .NET Framework and makes code more natural to read.



douse implicit type var for local variable declarations. Exception: primitive types (int, string,
double, etc) use predefined names.

    var stream = File.Create(path);
    var customers = new Dictionary();
     
    // Exceptions
    int index = 100;
    string timeSheet;
    bool isCompleted;

Why: removes clutter, particularly with complex generic types. Type is easily detected with Visual Studio tooltips.



douse noun or noun phrases to name a class.

    public class Employee
    {
    }
    public class BusinessLocation
    {
    }
    public class DocumentCollection
    {
    }

Why: consistent with the Microsoft's .NET Framework and easy to remember.



doprefix interfaces with the letter I. Interface names are noun (phrases) or adjectives.

    public interface IShape
    {
    }
    public interface IShapeCollection
    {
    }
    public interface IGroupable
    {
    }

Why: consistent with the Microsoft's .NET Framework.



doname source files according to their main classes. Exception: file names with partial classes
reflect their source or purpose, e.g. designer, generated, etc.

    // Located in Task.cs
    public partial class Task
    {
        //...
    }
    // Located in Task.generated.cs
    public partial class Task
    {
        //...
    }

Why: consistent with the Microsoft practices. Files are alphabetically sorted and partial classes remain adjacent.



doorganize namespaces with a clearly defined structure

    // Examples
    namespace Company.Product.Module.SubModule
    namespace Product.Module.Component
    namespace Product.Layer.Module.Group

Why: consistent with the Microsoft's .NET Framework. Maintains good organization of your code base.



dovertically align curly brackets.

    // Correct
    class Program
    {
        static void Main(string[] args)
        {
        }
    }

Why: Microsoft has a different standard, but developers have overwhelmingly preferred vertically aligned brackets.



dodeclare all member variables at the top of a class, with static variables at the very top.

    // Correct
    public class Account
    {
        public static string BankName;
        public static decimal Reserves;
     
        public string Number {get; set;}
        public DateTime DateOpened {get; set;}
        public DateTime DateClosed {get; set;}
        public decimal Balance {get; set;}
     
        // Constructor
        public Account()
        {
            // ...
        }
    }

Why: generally accepted practice that prevents the need to hunt for variable declarations.



douse singular names for enums. Exception: bit field enums.

    // Correct
    public enum Color
    {
        Red,
        Green,
        Blue,
        Yellow,
        Magenta,
        Cyan
    }
     
    // Exception
    [Flags]
    public enum Dockings
    {
        None = 0,
        Top = 1, 
        Right = 2, 
        Bottom = 4,
        Left = 8
    }

Why: consistent with the Microsoft's .NET Framework and makes the code more natural to read. Plural flags because enum can hold multiple values (using bitwise 'OR').



do notexplicitly specify a type of an enum or values of enums (except bit fields)

    // Don't
    public enum Direction : long
    {
        North = 1,
        East = 2,
        South = 3,
        West = 4
    }
     
    // Correct
    public enum Direction
    {
        North,
        East,
        South,
        West
    }

Why: can create confusion when relying on actual types and values.



do notsuffix enum names with Enum

    // Don't
    public enum CoinEnum
    {
        Penny,
        Nickel,
        Dime,
        Quarter,
        Dollar
    }
     
    // Correct
    public enum Coin
    {
        Penny,
        Nickel,
        Dime,
        Quarter,
        Dollar
    }

Why: consistent with the Microsoft's .NET Framework and consistent with prior rule of no type indicators in identifiers.



Tags:C#   点击:()  评论:()
声明:本站部分内容及图片来自互联网,转载是出于传递更多信息之目的,内容观点仅代表作者本人,如有任何标注错误或版权侵犯请与我们联系(Email:2595517585@qq.com),我们将及时更正、删除,谢谢。
▌相关推荐
本文告诉大家 await 的高级用法,包括底层原理。昨天看到太子写了一段代码,我开始觉得他修改了编译器,要不然下面的代码怎么可以编译通过await "林德熙逗比";需要知道,基本可以添...【详细内容】
2021-05-25  Tags: C#  点击:(218)  评论:(0)  加入收藏
Below are our C# coding standards, naming conventions, and best practices. Use these in your own projects and/or adjust these to your own needs. douse PascalCas...【详细内容】
2020-08-24  Tags: C#  点击:(116)  评论:(0)  加入收藏
介绍本文主要为C#开发人员了解Java提供一些基础。Java中缺少C#的功能 C#包含更多原始类型和捕获算术异常的功能。 包括大量的Java注释便利,其中许多,例如运算符重载和用户定义的...【详细内容】
2020-03-10  Tags: C#  点击:(62)  评论:(0)  加入收藏
▌简易百科推荐
一、简介很多时候我们都需要用到一些验证的方法,有时候需要用正则表达式校验数据时,往往需要到网上找很久,结果找到的还不是很符合自己想要的。所以我把自己整理的校验帮助类分...【详细内容】
2021-12-27  中年农码工    Tags:C#   点击:(1)  评论:(0)  加入收藏
引言在学习C语言或者其他编程语言的时候,我们编写的一个程序代码,基本都是在屏幕上打印出 hello world ,开始步入编程世(深)界(坑)的。C 语言版本的 hello world 代码:#include <std...【详细内容】
2021-12-21  一起学嵌入式    Tags:C 语言   点击:(10)  评论:(0)  加入收藏
读取SQLite数据库,就是读取一个路径\\192.168.100.**\position\db.sqlite下的文件<startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0"/...【详细内容】
2021-12-16  今朝我的奋斗    Tags:c#   点击:(21)  评论:(0)  加入收藏
什么是shellshell是c语言编写的程序,它在用户和操作系统之间架起了一座桥梁,用户可以通过这个桥梁访问操作系统内核服务。 它既是一种命令语言,同时也是一种程序设计语言,你可以...【详细内容】
2021-12-16  梦回故里归来    Tags:shell脚本   点击:(16)  评论:(0)  加入收藏
一、编程语言1.根据熟悉的语言,谈谈两种语言的区别?主要浅谈下C/C++和PHP语言的区别:1)PHP弱类型语言,一种脚本语言,对数据的类型不要求过多,较多的应用于Web应用开发,现在好多互...【详细内容】
2021-12-15  linux上的码农    Tags:c/c++   点击:(17)  评论:(0)  加入收藏
1.字符串数组+初始化char s1[]="array"; //字符数组char s2[6]="array"; //数组长度=字符串长度+1,因为字符串末尾会自动添&lsquo;\0&lsquo;printf("%s,%c\n",s1,s2[2]);...【详细内容】
2021-12-08  灯-灯灯    Tags:C语言   点击:(46)  评论:(0)  加入收藏
函数调用约定(Calling Convention),是一个重要的基础概念,用来规定调用者和被调用者是如何传递参数的,既调用者如何将参数按照什么样的规范传递给被调用者。在参数传递中,有两个很...【详细内容】
2021-11-30  小智雅汇    Tags:函数   点击:(19)  评论:(0)  加入收藏
一、问题提出问题:把m个苹果放入n个盘子中,允许有的盘子为空,共有多少种方法?注:5,1,1和1 5 1属同一种方法m,n均小于10二、算法分析设f(m,n) 为m个苹果,n个盘子的放法数目,则先对...【详细内容】
2021-11-17  C语言编程    Tags:C语言   点击:(46)  评论:(0)  加入收藏
一、为什么需要使用内存池在C/C++中我们通常使用malloc,free或new,delete来动态分配内存。一方面,因为这些函数涉及到了系统调用,所以频繁的调用必然会导致程序性能的损耗;另一...【详细内容】
2021-11-17  深度Linux    Tags:C++   点击:(37)  评论:(0)  加入收藏
OpenCV(Open Source Computer Vision Library)是一个(开源免费)发行的跨平台计算机视觉库,可以运行在Linux、Windows、Android、ios等操作系统上,它轻量级而且高效---由一系列...【详细内容】
2021-11-11  zls315    Tags:C#   点击:(50)  评论:(0)  加入收藏
最新更新
栏目热门
栏目头条