?? 運算符稱為 null 合並運算符,用於定義可以為 null 值的類型和引用類型的默認值。 如果此運算符的左操作數不為 null,則此運算符將返回左操作數;否則返回右操作數。
class NullCoalesce
{
static int? GetNullableInt()
{
return null;
}
static string GetStringValue()
{
return null;
}
static void Main()
{
// ?? operator example.
int? x = null;
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
// Assign i to return value of method, unless
// return value is null, in which case assign
// default value of int to i.
int i = GetNullableInt() ?? default(int);
string s = GetStringValue();
// ?? also works with reference types.
// Display contents of s, unless s is null,
// in which case display "Unspecified".
Console.WriteLine(s ?? "Unspecified");
}
}1:“按位與”運算符(&)用法是如果兩個相應的二進制位都為1,則該位的結果值為1否則為0。0&0=0,1&0=0,1&1=1
2:“按位或”運算符(|)用法是如果兩個相應的二進制位有一個為1,則該位的結果值為1否則為0。0&0=0,1&0=0,1&1=1
0,1&0=1,1&1=1
3:“異或”運算符(^)用法是如果兩個相應的二進制位為同號,則該位的結果值為1否則為0。0&0=1,1&0=0,1&1=1
條件運算符(?:)是C語言中唯一具的三目運算符,就是說它有三個運算對象。條件運算符的形式是"? :"由它構成的表達式稱為條件表達式
條件表達式的形式為:
表達式1 ? 表達式2 : 表達式3
例如:(a>b)?a+b:a-b
其中,如果a=2,b=1,那麼a>b成立,執行a+b這個表達式,運算結果為3;但如果a=2,b=3,那麼a>b不成立,那麼執行a-b這個表達式,運算結果為-1.