解析C#编程的通用结构和程序书写格式规范

2019-12-26 16:58:21于海丽

&& 和 || 运算符
若要通过跳过必要的比较来避免异常和提高性能,请在执行比较时使用 && 来代替 &,使用 || 来代替 | ,如下面的示例所示。


Console.Write("Enter a dividend: ");
var dividend = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter a divisor: ");
var divisor = Convert.ToInt32(Console.ReadLine());

// If the divisor is 0, the second clause in the following condition
// causes a run-time error. The && operator short circuits when the
// first expression is false. That is, it does not evaluate the
// second expression. The & operator evaluates both, and causes 
// a run-time error when divisor is 0.
if ((divisor != 0) && (dividend / divisor > 0))
{
  Console.WriteLine("Quotient: {0}", dividend / divisor);
}
else
{
  Console.WriteLine("Attempted division by 0 ends up here.");
}

New 运算符
隐式类型化时,请使用对象实例化的简洁形式,如下面的声明所示。


var instance1 = new ExampleClass();

上一行等同于下面的声明。


ExampleClass instance2 = new ExampleClass();

使用对象初始值设定项来简化对象创建。


// Object initializer.
var instance3 = new ExampleClass { Name = "Desktop", ID = 37414, 
  Location = "Redmond", Age = 2.3 };

// Default constructor and assignment statements.
var instance4 = new ExampleClass();
instance4.Name = "Desktop";
instance4.ID = 37414;
instance4.Location = "Redmond";
instance4.Age = 2.3;

事件处理
如果你正定义一个稍后不需要删除的事件处理程序,请使用 lambda 表达式。


 public Form2()
{
  // You can use a lambda expression to define an event handler.
  this.Click += (s, e) =>
    {
      MessageBox.Show(
        ((MouseEventArgs)e).Location.ToString());
    };
}


 // Using a lambda expression shortens the following traditional definition.
public Form1()
{
  this.Click += new EventHandler(Form1_Click);
}

void Form1_Click(object sender, EventArgs e)
{
  MessageBox.Show(((MouseEventArgs)e).Location.ToString());
}

 

静态成员
通过使用类名称调用静态成员:ClassName.StaticMember。这种做法通过明确静态访问使代码更易于阅读。请勿使用派生类的名称限定基类中定义的静态成员。编译该代码时,代码可读性具有误导性,如果向派生类添加具有相同名称的静态成员,代码可能会被破坏。