1、條件運算符
條件運算符(?:)也稱為三元(目)運算符,是if...else結構的簡化形式,可以嵌套使用。
int x = 1;
string s = x + ""; ;
s += (x == 1 ? "man" : "men");
Console.WriteLine(s);//輸出1man
2、checked和unchecked
byte b = 255;
{
b++;
}
Console.WriteLine(b.ToString());//輸出0
但是由于byte只能包含0-255的數,所以++之后會導致b溢出。因此,如果把一個代碼塊標記為checked,CLR就會執行溢出檢查,如果發生溢出,就拋出來OverflowException異常。
如下所示:
byte b = 255;
checked
{
b++;
}
Console.WriteLine(b.ToString());//拋出OverflowException異常,算術運算導致溢出
如果要禁止溢出檢查,可以標記為unchecked:
byte b = 255;
unchecked
{
b++;
}
Console.WriteLine(b.ToString());//輸出0,不拋異常
3、is
is運算符可以檢查對象是否與特定的類型兼容。“兼容”表示對象是該類型或者派生自該類型。
string i = "hello i...";
if (i is object)
{
Console.WriteLine("i is an object...");//執行了這句話
}
4、as
as運算符用于執行引用類型的顯式類型轉換(string 為引用類型)。如果要轉換的類型與指定的類型兼容,轉換就會成功進行;如果類型不兼容,as運算符就會返回Null。
string i = "hello i...";
if (i is object)
{
object obj = i as object;//顯式類型轉換
Console.WriteLine(obj is string ? "obj is string..." : "obj is not string...");//輸出obj is string...
}
5、sizeof
sizeof運算符可以確定stack中值類型需要的長度(單位是字節):
int byteSize = sizeof(byte);//輸出1
int charSize = sizeof(char);//輸出2
int uintSize = sizeof(uint);//輸出4
int intSize = sizeof(int);//輸出4
6、typeof
typeof運算符常常會跟GetType()方法結合使用,來反射出類的屬性、方法等。
Type intType = typeof(int);
System.Reflection.MethodInfo[] methodInfo = intType.GetMethods();
methodInfo.ToList().ForEach(x => Console.WriteLine(x.Name));//反射出int類型的方法名
7、可空類型和運算符
如果其中一個操作數或兩個操作數都是null,其結果就是null,如:
int? a = null;
int? b = a + 4;//b = null
int? c = a * 5;//c = null
但是在比較可空類型時,只要有一個操作數為null,比較的結果就是false。但不能因為一個條件是false,就認為該條件的對立面是true。如:
int? a = null;
int? b = -5;
if (a >= b)
Console.WriteLine("a > = b");
else
Console.WriteLine("a < b");//會輸出這句話
8、空合并運算符
例如:
int? a = null;//加問號,是為了能夠給Int型賦值為null
int b;
b = a ?? 1;
[csharp]
Console.WriteLine(b);//輸出1
a = 3;
b = a ?? 10;
Console.WriteLine(b);//輸出10