C# 语言中表达式的分类
- A value. Every value has an associated type.
回顾上一节讲的操作符,并讲解由这些操作符组成的表达式所返回的类型。
条件操作符
?:
总会返回精度高的那个类型:var x = 5>3?2:3.0;
Console.WriteLine(x.GetType().FullName);
// System.Double
A variable(变量). Every variable has an associated type.
int x = 100;
int y;
y = x;
A namespace.
System.Windows.Forms.Form myForm = new Form();
A type.
var t = typeof(Int32);
A method group
Console.WriteLine
,这是一组方法(19 种重载),重载决策决定具体调用那种方法。A null literal.
null 值也是一个值。Form myForm = null;
A property access.
- An event access. ```csharp static void Main(string[] args) { var myForm = new Form(); // 访问属性 myForm.Text = “Hello”; // 访问事件 myForm.Load += MyForm_Load; myForm.ShowDialog(); }
private static void MyForm_Load(object sender, EventArgs e) { var form = sender as Form; if (form == null) { return; }
form.Text = "New Title";
}
- An indexer access.
```csharp
var intList = new List<int>() {1, 2, 3 };
var x = intList[2];
- Nothing.对返回值为 void 方法的调用
复合表达式的求值
C#语言定义文档里面未明确定义复合表达式,但确实常用。
注意操作符的优先级和同优先级操作符的运算方向(除了赋值操作符,基本都是从左向右)。