zoukankan      html  css  js  c++  java
  • C#编码好习惯,献给所有热爱c#的同志(转)(2)

    23.  Avoid friend assemblies, as it increases inter-assembly coupling.

    24.  Avoid code that relies on an assembly running from a particular location.

    25. 
    使应用程序集尽量为最小化代码(EXE客户程序)。使用类库来替换包含的商务逻辑。

    26. 
    避免给枚举变量提供显式的值。

    //
    正确方法 

    public enum Color

    {   

      Red,Green,Blue

    }

    //
    避免

    public enum Color

    {   

      Red = 1,Green =  2,Blue = 3

    }

    27. 
    避免指定特殊类型的枚举变量。

    //
    避免 

    public enum Color  : long

    {   

      Red,Green,Blue

    }

    28. 
    即使if语句只有一句,也要将if语句的内容用大括号扩起来。

    29. 
    避免使用trinary条件操作符。

    30. 
    避免在条件语句中调用返回bool值的函数。可以使用局部变量并检查这些局部变量。

    bool IsEverythingOK()

    {…}

    //
    避免

    if (IsEverythingOK ())

    {…}

    //
    替换方案 

    bool ok = IsEverythingOK();

    if (ok)

    {…}

    31. 
    总是使用基于0开始的数组。

    32. 
    在循环中总是显式的初始化引用类型的数组。

    public class MyClass

    {}

    MyClass[] array = new  MyClass[100];

    for(int index = 0; index < array.Length;  index++)

    {

      array[index] = new  MyClass();

    }

    33. 
    不要提供public protected的成员变量,使用属性代替他们。

    34. 
    避免在继承中使用new而使用override替换。

    35. 
    在不是sealed的类中总是将public protected的方法标记成virtual的。

    36. 
    除非使用interop(COM+ 或其他的dll)代码否则不要使用不安全的代码(unsafe code)

    37. 
    避免显示的转换,使用as操作符进行兼容类型的转换。

    Dog dog = new GermanShepherd();

    GermanShepherd shepherd = dog  as  GermanShepherd;

    if (shepherd != null )

    {…}

    38. 
    当类成员包括委托的时候

    a)  Copy a delegate to a local variable before publishing to avoid concurrency race

    condition. 

    b) 
    在调用委托之前一定要检查它是否为null

    public class MySource

    {

      public event EventHandler  MyEvent;

      public void FireEvent()

      {

          EventHandler temp = MyEvent;

          if(temp != null )

          {

            temp(this,EventArgs.Empty);

          }

      }



    39. 
    不要提供公共的事件成员变量,使用事件访问器替换这些变量。

    public class MySource

    {

      MyDelegate m_SomeEvent ;

      public event MyDelegate SomeEvent

      {

          add

          {

            m_SomeEvent += value;

          }

          remove

          {

            m_SomeEvent -= value;

          }

      }

    }

    40. 
    使用一个事件帮助类来公布事件的定义。

    41. 
    总是使用接口。

    42. 
    类和接口中的方法和属性至少为2:1的比例。

    43. 
    避免一个接口中只有一个成员。

    44. 
    尽量使每个接口中包含35个成员。
  • 相关阅读:
    45.如何优雅的删除一张大表?
    13.安装上传和下载文件
    12.yum install 和yum localinstall区别
    7.Mysql之MGR环境搭建
    mod运算
    取整
    同余式
    Windows下的重定向
    C语言求正负余数
    复利计算公式
  • 原文地址:https://www.cnblogs.com/soso_ak/p/1433501.html
Copyright © 2011-2022 走看看