1 |
[SerializableAttribute] |
2 |
public struct Nullable<T> where T : struct , new () |
C#裏像int, bool, double這樣的struct和enum類型都不能爲null。若是確實想在值域上加上null的話,Nullable就派上用場了。T?是Nullable&ly;T>的語法糖。要將T?轉爲T能夠經過類型轉換,或者經過T?的Value屬性,固然後者要高雅些。express
1 |
// Nullable<int> arg = -1; |
2 |
int ? arg = -1; |
3 |
if (arg.HasValue) { |
4 |
// int value = (int)arg; |
5 |
int value = arg.Value; |
6 |
} |
o ?? v能夠看做是o == null ? v : o的語法糖。??運算符在左操做數非null時返回左操做數,不然返回右操做數。spa
1 |
string result = gao(); |
2 |
Console.WriteLine(result ?? "<NULL>" ); |
看別人代碼的過程當中才發現原來C#也有lambda了,也才發現本身真的out了。固然,感受C#裏的lambda並無帶來什麼革命性的變化,更像是一個語法糖。畢竟這不是Scale,MS也有F#了。code
1 |
Func< double , double , double > hypot = (x, y) => Math.Sqrt(x * x + y * y); |
2 |
Func< double , double , string > gao = (x, y) => |
3 |
{ |
4 |
double z = hypot(x, y); |
5 |
return String.Format( "{0} ^ 2 + {1} ^ 2 = {2} ^ 2" , x, y, z); |
6 |
}; |
7 |
Console.WriteLine(gao(3, 4)); |
collection initializer使得初始化一個List, Dictionary變得簡單。orm
1 |
List< string > list = new List< string >{ "watashi" , "rejudge" }; |
2 |
Dictionary< string , string > dic = new Dictionary< string , string > |
3 |
{ |
4 |
{ "watashi" , "watashi wa watashi" }, |
5 |
{ "rejudge" , "-rejudge -pia2dea4" } |
6 |
}; |
而object initializer其實就是調用完成構造後執行屬性操做的語法糖,它使得代碼更加簡潔,段落有致。試比較:ip
1 |
Sequence activity = new Sequence() |
2 |
{ |
3 |
DisplayName = "Root" , |
4 |
Activities = |
5 |
{ |
6 |
new If() |
7 |
{ |
8 |
Condition = true , |
9 |
Else = new DoWhile() |
10 |
{ |
11 |
Condition = false |
12 |
} |
13 |
}, |
14 |
new WriteLine() |
15 |
{ |
16 |
DisplayName = "Hello" , |
17 |
Text = "Hello, World!" |
18 |
} |
19 |
} |
20 |
}; |
1 |
Sequence activity2 = new Sequence(); |
2 |
activity2.DisplayName = "Root" ; |
3 |
4 |
If if2 = new If(); |
5 |
if2.Condition = true ; |
6 |
DoWhile doWhile2 = new DoWhile(); |
7 |
doWhile2.Condition = false ; |
8 |
if2.Else = doWhile2; |
9 |
activity2.Activities.Add(if2); |
10 |
11 |
WriteLine writeLine2 = new WriteLine(); |
12 |
writeLine2.DisplayName = "Hello" ; |
13 |
writeLine2.Text = "Hello, World!" ; |
14 |
activity2.Activities.Add(writeLine2); |
又是一個方便的語法糖,只要簡單的一句ci
1 |
public string Caption { get ; set ; } |
就能夠代替原來的一大段代碼。get
1 |
private string caption; |
2 |
public string Caption |
3 |
{ |
4 |
get |
5 |
{ |
6 |
return caption; |
7 |
} |
8 |
set |
9 |
{ |
10 |
caption = value; |
11 |
} |
12 |
} |
var並非表明任意類型,畢竟C#是個強類型的語言。var只是個在聲明變量時代替實際的類型名的語法糖,只能使用在編譯器能根據上下文推出其實際類型的地方。這在類型名稱藏在好幾層namespace或class裏的時候,還有在foreach語句中很是有用。編譯器
1 |
foreach (var a in dict) |
2 |
{ |
3 |
Console.WriteLine( "{0} => {1}" , a.Key, a.Value); |
4 |
} |