您所在的位置: 首页 > 开发 > .Net > c# >

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

http://developer.51cto.com  2006-01-25 17:16  杨贺宏 译  tb.blog.csdn.net  我要评论(0)
  • 摘要:本文介绍在C# 编码的时候需要遵守的规范,以及程序员应该养成的编程好习惯……
  • 标签:C#

命名惯例和规范
注记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++)
       {
        //
       }
      }
    
  • 良好的编程习惯


    共2页: 1 [2] 下一页
    【内容导航】
  • C#实用基础教程
    C#技术开发指南
    Scala编程语言
    大型网站架构技术专家谈
    ASP.NET视频教程
     
     验证码: (点击刷新验证码)   匿名发表
    • 亮剑.NET. 图解C#开发实战

    • 作者:李新峰 付志涛 缪勇
    • 本书采用全新的图解思路,分3篇介绍使用微软C#语言开发实际应用程序的基本知识。第1篇包括10章,介绍了C#语言的基础知识,主要..
    Copyright©2005-2009 51CTO.COM 版权所有