您所在的位置:开发 > .NET > C# > C# 编码规范和编程好习惯(1)

C# 编码规范和编程好习惯(1)

2006-01-25 17:16 杨贺宏 译 tb.blog.csdn.net 我要评论(0) 字号:T | T
一键收藏,随时查看,分享好友!

本文介绍在C# 编码的时候需要遵守的规范,以及程序员应该养成的编程好习惯……

AD:

命名惯例和规范
注记Pascal 大小写形式-所有单词第一个字母大写,其他字母小写。
Camel大小写形式-除了第一个单词,所有单词第一个字母大写,其他字母小写。

  • 类名使用Pascal 大小写形式
    public class HelloWorld
    { ...
    }
    
  • 方法使用Pascal 大小写形式
    public class HelloWorld
    {
     void SayHello(string name)
     {
      ...
     }
    }<
  • 变量和方法参数使用Camel 大小写形式
    public class HelloWorld
    {
     int totalCount = 0;
     void SayHello(string name)
     {
      string fullMessage = "Hello " + name;
      ...
     }
    }
    
  • 不要使用匈牙利方法来命名变量
    以前,多数程序员喜欢它-把数据类型作为变量名的前缀而m_作为成员变量的前缀。例如:
    string m_sName;
    int nAge;
    
    然而,这种方式在.NET编码规范中是不推荐的。所有变量都用camel 大小写形式,而不是用数据类型和m_来作前缀。
  • 用有意义的,描述性的词语来命名变量
    - 别用缩写。用name, address, salary等代替 nam, addr, sal
    - 别使用单个字母的变量象i, n, x 等. 使用 index, temp等
    用于循环迭代的变量例外:
    for ( int i = 0; i < count; i++ )
    {
     ...
    }
    
    如果变量只用于迭代计数,没有在循环的其他地方出现,许多人还是喜欢用单个字母的变量(i) ,而不是另外取名。
    - 变量名中不使用下划线 (_) 。
    - 命名空间需按照标准的模式命名
    ...
    
  • 文件名要和类名匹配
    例如,对于类HelloWorld, 相应的文件名应为 helloworld.cs (或, helloworld.vb)

    缩进和间隔

  • 缩进用 TAB . 不用 SPACES.。
  • 注释需和代码对齐.。
  • 花括弧 ( {} ) 需和括号外的代码对齐.。
  • 用一个空行来分开代码的逻辑分组。.
     bool SayHello (string name)
     {
      string fullMessage = "Hello " + name;
      DateTime currentTime = DateTime.Now;
      string message = fullMessage + ", 
    the time is: " + currentTime.ToShortTimeString();
      MessageBox.Show ( message );
      if ( ... )
      {
       // Do something
       // ...
       return false;
      }
      return true;
     }
    这段代码看起来比上面的好:
     bool SayHello ( string name )
     {
      string fullMessage = "Hello " + name;
      DateTime currentTime = DateTime.Now;
      
    string message = fullMessage + ",
    the time is: " + currentTime.ToShortTimeString();
      
    MessageBox.Show ( message );
    if ( ... ) { // Do something // ...
    return false; }
    return true; }
  • 在一个类中,各个方法需用一空行,也只能是一行分开。
  • 花括弧需独立一行,而不象if, for 等可以跟括号在同一行。
    好:
     if ( ... ) 
    { // Do something
      }
    
    不好:
      if ( ... ) {
       // Do something
      }
    
  • 在每个运算符和括号的前后都空一格。.
    好:
      if ( showResult == true )
      {
       for ( int i = 0; i < 10; i++ )
       {
        //
       }
      }
    
    不好:
      if(showResult==true)
      {
       for(int i= 0;i<10;i++)
       {
        //
       }
      }
    
  • 良好的编程习惯

    内容导航

  • 网友评论TOP5

    查看所有评论(

    提交评论

    1. 编程排行榜:图形编程的LOGO语言
    2. 什么是响应式Web设计?

    热点专题

    更多>>

    读书

    Visual Studio 2005+SQL Server 2005数据库应用系
    本书主要介绍采用Visual Studio 2005的C#语言为前台,SQL Server 2005数据库为后台的数据库系统开发技术。 全书分为15章,内容

    51CTO旗下网站

    领先的IT技术网站 51CTO 领先的中文存储媒体 WatchStor 中国首个CIO网站 CIOage 中国首家数字医疗网站 HC3i 移动互联网生活门户 灵客风LinkPhone