C#運算符表達式淺析
C#運算符表達式的幾種常見使用如下
常見的C#運算符表達式
- static void Main()
- {
- int result = 0;//=為賦值運算符,這是一個賦值表達式.
- int number;
- result = number * 100;//這是一個表達式,=為賦值運算符,*為算術運算符
- Console.WriteLine(result);//這里的.號就指成員訪問運算符
- }
一元運算符(++/--)及表達式
- static void Main()
- {
- int inti = 0;//聲明變量
- int intj = 0;
- for (int i = 0; i < 10; i++)
- {
- inti++;
- intj--;
- }
- Console.WriteLine("inti++運算后結果為{0},intj--運算后結果為{1}", inti, intj);
- }
- //運行結果為inti=10,intj=-10
由此可見,inti++相當于inti=inti+1,而intj--相當于intj=intj-1.
三元C#運算符表達式
static void Main()
- {
- int inti = 1;//聲明變量
- string sex = inti.ToString()+" ";
- sex += (inti == 1 ? "男人" : "女人");//如果inti為1 時候sex為男人,否則的話sex為女人
- Console.WriteLine(sex);
- }
三元運算符還是常用滴.希望能多練練.
C#運算符表達式之is操作符:
is操作符是用來動態的檢測運行時對像類型是否與指定類型兼容,運算結果返回一個bool值,例:
- public static void Main()
- {
- Console.WriteLine(1 is int);
- Console.WriteLine(1 is float);
- Console.WriteLine(1.0 is float);
- Console.WriteLine(1.0 is double);
- }
以上代碼的返回結果為:true false false true
需要注意的是,我們能表述的意思是 蘋果是水果,得到的答案為true.
C#運算符表達式之as操作符:
as操作符應用于兼容的引用類型之間的轉換.返回值為值本身或null.如:
- public static void Main()
- {
- Console.WriteLine(“a” as string);
- }
以上內容基本敘述了C#中的運算符及表達式,如果無法明白或有錯誤的地方,請回復指證,謝謝大家.
C#運算符表達式的相關內容就向你介紹到這里,希望對你了解C#運算符表達式有所幫助。
【編輯推薦】