C#基礎語法 — (5)操作符詳解


一、操作符概覽

在這裏插入圖片描述

  • 操作符(Operator)也譯爲“運算符”
  • 操作符是用來操作數據的,被操作符操作的數據稱爲操作數(Operand)

二、操作符的本質

  • 操作符的本質是函數(即算法)的“簡記法”
    • 假如沒有發明“+”,只有 Add 函數,算式 3+4+5將可以寫成 Add(Add(3,4),5)
    • 假如沒有發明“*”,只有 Mul 函數,那麼算式 3+4*5 只能寫成 Add(3,Mul(4,5))
  • 操作符不能脫離與它關聯的數據類型
    • 可以說操作符就是與固定數據類型相關聯的一套基本算法的簡記法
    • 示例:爲自定義數據類型創建操作符

下例中的操作符+ 就是 GetMarry 方法的簡記:

namespace CreateOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            Person person1 = new Person();
            Person person2 = new Person();
            person1.Name = "Deer";
            person2.Name = "Deer's wife";
            //List<Person> nation = Person.GetMarry(person1, person2);
            List<Person> nation = person1 + person2;
            foreach (var p in nation)
            {
                Console.WriteLine(p.Name);
            }
        }
    }

    class Person
    {
        public string Name;

        //public static List<Person> GetMarry(Person p1, Person p2)
        public static List<Person> operator +(Person p1, Person p2)//操作符+
        {
            List<Person> people = new List<Person>();
            people.Add(p1);
            people.Add(p2);
            for (int i = 0; i < 11; i++)
            {
                Person child = new Person();
                child.Name = p1.Name + "&" + p2.Name + "'s child";
                people.Add(child);
            }
            return people;
        }
    }
}

三、優先級與運算順序

  • 操作符的優先級
    • 可以使用圓括號提高被括起來表達式的優先級
    • 圓括號可以嵌套
    • 不像數學裏有方括號與花括號,在 C# 語言裏面“[]”與“{}”有專門的用途
  • 同優先級操作符的運算順序
  • 除了帶有賦值功能的操作符,同優先級操作符都由左向右進行運算
  • 帶有賦值功能的操作符的運算順序是由右向左
  • 與數學運算不同,計算機語言的同優先級運算沒有“結合率”
    • 3+4+5 只能理解爲 Add(Add(3,4),5) 不能理解爲 Add(3,Add(4,5))

同優先級操作符的運算順序:

    class Program
    {
        static void Main(string[] args)
        {
            int x;
            x = 3 + 4 + 5;//"+"比"="優先級高,先算"+";兩個"+"優先級一樣,從左往右;最後賦給x
            Console.WriteLine(x);//x=12            
        }
    } 
        static void Main(string[] args)
        {
            int x = 100;
            int y = 200;
            int z = 300;

            x += y += z;//y=y+z;x=x+(y+z);

            Console.WriteLine(x);//600
            Console.WriteLine(y);//500
            Console.WriteLine(z);//300
        }
    }

四、各類操作符的示例

在這裏插入圖片描述

1.基本操作符

. 成員訪問操作符

功能:
  1.訪問外層名稱空間中的子名稱空間
  2.訪問名稱空間中的類型
  3.訪問類型的靜態成員
  4.訪問對象中的實例成員

System.IO.File.Create("D:\\HelloWorld.txt");
      1  2    3

Form myForm = new Form();
myForm.Text = "Hello, World";
      4
myForm.ShowDialog();
      4

f(x) 方法調用操作符

  方法調用操作符就是方法後面的那對()
  f是function的縮寫,()中的x指的是方法調用時的參數。

  方法名後面不一定要有()
  Action 是委託,委託在創建時只需要知道方法的名稱,不調用方法,所以只會用到方法名(不加())。當然最終ac();也用到了方法調用操作符()。

namespace CreateOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            Calculator c = new Calculator();

            double x = c.Add(3.0, 5.0);//調用Add方法
            Console.WriteLine(x);

            Action ac = new Action(c.PrintHello);//訪問c.PrintHello這個成員,而不是調用PrintHello方法
            ac();//調用被ac管理的方法—PrintHello()
        }
    }

    class Calculator
    {
        public double Add(double a, double b)
        {
            return a + b;
        }

        public void PrintHello()
        {
            Console.WriteLine("Hello World");
        }
    }
}

a[x] 元素訪問操作符

訪問數組元素:

namespace CreateOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] myArray = new int[10];//創建長度爲10的數組
            Console.WriteLine(myArray[0]);

            int[] myArray1 = new int[] { 1, 2, 3, 4, 5 };//創建含有這幾個元素的數組
            Console.WriteLine(myArray1[0]);

            int[] myArray2 = new int[3] { 1, 2, 3 };//創建數組
            Console.WriteLine(myArray2[0]);
        }
    }
}

訪問字典中的元素:

namespace CreateOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, Student> stuDic = new Dictionary<string, Student>();
            for (int i = 1; i < 101; i++)
            {
                Student stu = new Student();
                stu.Name = "s_" + i.ToString();
                stu.Score = 100 + i;
                stuDic.Add(stu.Name, stu);
            }

            //訪問s_6的學生的成績
            Student number6 = stuDic["s_6"];
            Console.WriteLine(number6.Score);
        }
    }

    class Student
    {
        public string Name;
        public int Score;
    }
}

x++ x-- 後置自增、自減操作符

namespace CreateOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 100;
            x++;//x=x+1;
            Console.WriteLine(x);//x=101

            int y = 100;
            y--;//y=y-1;
            Console.WriteLine(y);//y=99

            int a = 100;
            int b = a++;//a=a+1;先賦值再自增
            Console.WriteLine(a);//101
            Console.WriteLine(b);//100        
        }
    }  
}

typeof 操作符

  查看類型的內部結構—檢測類型元數據(Metadata)

    class Program
    {
        static void Main(string[] args)
        {
            //查看int類型的內部結構
            Type t = typeof(int);
            Console.WriteLine(t.Namespace);//名稱空間:System
            Console.WriteLine(t.FullName);//全名:System.Int32
            Console.WriteLine(t.Name);//不帶名稱空間的名字:Int32

            //查看int的所有方法
            int c = t.GetMethods().Length;
            foreach (var mi in t.GetMethods())
            {
                Console.WriteLine(mi.Name);//方法的名字
            }
            Console.WriteLine(c);
        }
    } 

default 操作符

  獲取一個類型的默認值

namespace CreateOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            //結構體類型;值類型內存塊都刷成0,值就是0
            int x = default(int);
            Console.WriteLine(x);//默認值0

            //引用類型;內存塊都刷成0,值就是null
            Form myForm = default(Form);
            Console.WriteLine(myForm == null);//True            

            //枚舉類型
            //枚舉類型映射到整型上,默認枚舉值是對應值爲 0 的那個,可能是你手動指定的,也可能是系統默認賦值的。
            //這就牽扯到我們使用枚舉時,要注意枚舉中是否有對應 0 的;創建枚舉類型時,最好有一個對應 0 的,以免他人查找我們枚舉的 default 值時報錯。
            Level level = default(Level);
            Console.WriteLine(level);
        }
    }

    //聲明枚舉類型
    enum Level
    {       
        Mid = 1,
        Low = 0,
        High = 2
    }
}

new 操作符

new當作操作符使用:

顯式類型與隱式類型的變量

//顯式類型的變量
int x;//在聲明變量時,明顯的告訴編譯器變量的數據類型是什麼

//隱式類型的變量
var x1 = 100;//在聲明變量時,數據類型由編譯器根據所賦的值來推斷
Console.WriteLine(x1.GetType().Name);//Int32

在內存中創建類型實例,並立刻調用實例構造器
把實例的內存地址通過賦值操作符交給訪問它的變量;通過變量來訪問實例

//在內存中創建類型實例,並立刻調用實例構造器
//把實例的內存地址通過賦值操作符交給訪問它的變量;通過變量來訪問實例
var MyForm = new Form();
MyForm.Text = "Hello";
MyForm.ShowDialog();

new操作符還可以調用實例的初始化器

var MyForm = new Form() {Text="Hello"};//{}爲實例的屬性設置值          
MyForm.ShowDialog();
var MyForm = new Form() //{}初始化器中有多個屬性
{
	Text = "Hello",
    FormBorderStyle = FormBorderStyle.SizableToolWindow
 };
MyForm.ShowDialog();
// new 一次性變量:利用實例的初始化器直接 new 對象後,馬上執行方法,然後就不管它了,隨着 GC 去處理它
new Form() {Text = "Hello"}.ShowDialog();

C#的語法糖衣,聲明基本數據類型的變量時可以不需要new操作符

            //C#的語法糖衣,聲明基本數據類型的變量時可以不需要new操作符           
            string name = "Tim";
            string name1 = new string(new char[] { 'T', 'i', 'm' });
            Console.WriteLine(name1);//Tim

            int[] myArray = new int[10];
            int[] myArray1 = { 1, 2, 3, 4 };

爲匿名類型創建對象

        static void Main(string[] args)
        {
            //非匿名類型
            Form myForm = new Form() { Text = "Hello" };

            //爲匿名類型創建實例,並用隱式類型變量來引用實例
            var person = new { Name = "Mr.Okay", Age = 34 };
            Console.WriteLine(person.Name);
            Console.WriteLine(person.Age);
            Console.WriteLine(person.GetType().Name);//<>f__AnonymousType0`2
        }

在這裏插入圖片描述

new 操作符會導致依賴緊耦合,可以通過依賴注入模式來將緊耦合變成相對鬆的耦合。

// new 操作符功能強大,但會造成依賴。創建實例後,Program類 就依賴到 Form類 上了,
// 一旦 Form類 運行出錯,Program類 也會出問題。
// 通過設計模式中的依賴注入模式來將緊耦合變成相對鬆的耦合
    class Program
    {
        static void Main(string[] args)
        {           
            Form myForm = new Form() { Text = "Hello" };     
        }
    }

new當作關鍵字使用:

namespace CreateOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            stu.Report();
            CsStudent csStu = new CsStudent();
            csStu.Report();   
        }
    }

    class Student
    {
        public void Report()
        {
            Console.WriteLine("I'm a student!");
        }
    }

    class CsStudent:Student//繼承自父類Student
    {
        //new修飾符;子類對父類方法進行隱藏
        new public void Report()
        {
            Console.WriteLine("I'm CS Student");
        }
    }
}

checked & unchecked 操作符

  檢查一個值在內存中是否有溢出。
  checked 時,x+1 直接就溢出變成 0 了。

        static void Main(string[] args)
        {
            uint x = uint.MaxValue;
            Console.WriteLine(x);
            string binStr = Convert.ToString(x, 2);
            Console.WriteLine(binStr);

            uint y = x + 1;//溢出;超出了數據類型大小範圍
            Console.WriteLine(y);//值爲0            
        }

在這裏插入圖片描述

   使用checked操作符

    class Program
    {
        static void Main(string[] args)
        {
            uint x = uint.MaxValue;
            Console.WriteLine(x);
            string binStr = Convert.ToString(x, 2);
            Console.WriteLine(binStr);            

            try
            {
                uint y = checked(x + 1);//溢出;超出了數據類型範圍
                Console.WriteLine(y);
            }
            catch (OverflowException ex)
            {

                Console.WriteLine("There's overflow!");
            }
        }
    }

在這裏插入圖片描述

  使用unchecked操作符

try
{
    // C# 默認採用的就是 unchecked 模式
    uint y = unchecked(x + 1);
    Console.WriteLine(y);
}
catch (OverflowException ex)
{
    Console.WriteLine("There's overflow!");
}

  checked 與 unchecked 作爲關鍵字

    class Program
    {
        static void Main(string[] args)
        {
            uint x = uint.MaxValue;
            Console.WriteLine(x);
            string binStr = Convert.ToString(x, 2);
            Console.WriteLine(binStr);

            checked //checked關鍵字
            {
                try
                {
                    uint y = x + 1;//溢出;超出了數據類型範圍
                    Console.WriteLine(y);
                }
                catch (OverflowException ex)
                {

                    Console.WriteLine("There's overflow!");
                }
            }            
        }
    }

delegate 操作符

  現在常見的是把 delegate 當做委託關鍵字使用。
  delegate 也可以作爲操作符使用,但由於 Lambda 表達式的流行,delegate 作爲操作符的場景愈發少見(被 Lambda 替代,已經過時)。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        // 方法封裝提高了複用性,但如果我這個方法在別的地方不太可能用到,我就可以使用匿名方法
        // 下面就是使用 delegate 來聲明匿名方法
        //this.myButton.Click += delegate (object sender, RoutedEventArgs e)
        //{
        //    this.myTextBox.Text = "Hello, World!";
        //}; 

        // 現在推薦使用的是 Lambda 表達式
        this.myButton.Click += (sender, e) =>
        {
            this.myTextBox.Text = "Hello, World!";
        };
    }

    // 非匿名方法
    //private void MyButton_Click(object sender, RoutedEventArgs e)
    //{
    //    throw new NotImplementedException();
    //}
}

sizeof 操作符

  sizeof用於獲取對象在內存中所佔字節數。
注意:
  1.默認情況下,sizeof 只能用於獲取基本數據類型的實例在內存中的字節數(string、object不行,因爲只能獲取結構體類型的實例在內存中的字節數)
  2.非默認情況下,可以使用 sizeof 獲取自定義結構體類型的實例在內存中所佔的字節數,但需要把它放在不安全的上下文中。

  需要在“項目屬性”裏面開啓“允許不安全代碼”。在這裏插入圖片描述

namespace SizeofSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //默認情況下
            int x = sizeof(int);
            Console.WriteLine(x);//4個字節

            int x1 = sizeof(long);
            Console.WriteLine(x1);//8個字節

            int x2 = sizeof(double);
            Console.WriteLine(x2);//8個字節

            int x3 = sizeof(decimal);
            Console.WriteLine(x3);//16個字節

            //非默認情況下
            unsafe
            {
                int y = sizeof(Student);
                Console.WriteLine(y);//16個字節
            }

        }
    }
 
    struct Student
    {
        int ID;
        long Socre;
    }
}

-> 操作符

  -> 操作符也必須放在不安全的上下文中才能使用。
  C# 中指針操作、取地址操作、用指針訪問成員的操作,只能用來操作結構體類型,不能用來操作引用類型。

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            unsafe
            {
                Student stu;
                stu.ID = 1;
                stu.Score = 99;
                Student* pStu = &stu;
                pStu->Score = 100;//通過指針訪問對象
                Console.WriteLine(stu.Score);
            }
        }
    }

    struct Student
    {
        public int ID;
        public long Score;
    }
}

2.一元操作符

&x*x 操作符

  也需要在不安全的上下文中。

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            unsafe
            {
                Student stu;
                stu.ID = 1;
                stu.Score = 99;
                Student* pStu = &stu;//&-取地址操作符
                pStu->Score = 100;//通過指針訪問對象
                (*pStu).Score = 1000;//*-取引用操作符
                Console.WriteLine(stu.Score);
            }
        }
    }

    struct Student
    {
        public int ID;
        public long Score;
    }
}

+ - 正負操作符 與 ~ 取反操作符

			int x = 100;
            int y = +x;
            Console.WriteLine(y);//100

            int x1 = 100;
            int y1 = -x1;
            Console.WriteLine(y1);//-100

            int x2 = 100;
            int y2 = -(-x2);
            Console.WriteLine(y2);//100

  正負操作符使用不當,可能導致溢出。
  -操作符 相當於是 按位取反再加一

			int x = int.MinValue;
            int y = checked(-x);//OverflowException
            Console.WriteLine(y);


			//相反數 = 按位取反再加一
            int a = 123;
            int b = -a;//a的相反數
            int c = ~a;//對a按位取反

            string aStr = Convert.ToString(a, 2).PadLeft(32, '0');//變量a的二進制形式
            string bStr = Convert.ToString(b, 2).PadLeft(32, '0');
            string cStr = Convert.ToString(c, 2).PadLeft(32, '0');
        
            Console.WriteLine("a的相反數:"+bStr+"\n");
            Console.WriteLine("a按位取反:"+cStr);//再加一 就等於 相反數

在這裏插入圖片描述

! 取非操作符

  只能用來操作 布爾類型 的值

  			bool b1 = true;
            bool b2 = !b1;

            Console.WriteLine(b2);//False

  取非操作符在實際中的應用

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {            
            Student stu = new Student(null);
            Console.WriteLine(stu);

            
        }
    }

    class Student
    {
        //自定義構造器
        public Student(string initName)
        {
            if (!string.IsNullOrEmpty(initName))//若字符串非空
            {
                this.Name = initName;
            }
            else
            {
                throw new ArgumentException("initName cannot be null or empty!");
            }            
        }

        public string Name;
    }
}

++x --x 前置自增自減操作符

  無論前置、後置,在實際工作中,儘量單獨使用它們,不要把它們和別的語句混在一起,那樣會降低可讀性。

        static void Main(string[] args)
        {
            int x = 100;
            int y = x++;//先賦值再自增
            Console.WriteLine(x);//101
            Console.WriteLine(y);//100

            int x1 = 100;
            int y1 = ++x1;//先自增再賦值
            Console.WriteLine(x1);//101
            Console.WriteLine(y1);//101            
        }

(T)x 強制類型轉換操作符

  • 隱式(implicit)類型轉換
    • 不丟失精度的轉換
    • 子類向父類的轉換
    • 裝箱
  • 顯式(explicit)類型轉換
    • 有可能丟失精度(甚至發生錯誤)的轉換,即cast
    • 拆箱
    • 使用Convert類
    • ToString方法與各數據類型的Parse/TryParse方法
  • 自定義類型轉換操作符

隱式類型轉換

在這裏插入圖片描述

  不丟失精度的隱式類型轉換

			int x = int.MaxValue;
            long y = x;//隱式類型轉換 int → long
            Console.WriteLine(y);

  子類向父類的轉換
(拿一個引用變量去訪問它所引用着的實例的成員的時候;只能訪問到變量的類型它所具有的成員。
而不是訪問變量所引用的實例的類型)

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            Teacher t = new Teacher();
            Human h = t;//子類向父類的隱式類型轉換
            //拿一個引用變量去訪問它所引用着的實例的成員的時候;只能訪問到變量的類型,它所具有的成員。
            //而不是訪問變量所引用的實例的類型
            h.Eat(); //只有Eat()和Think()方法

            //Animal a = h;
            //a.Eat();//只有Eat()方法
        }
    }

    class Animal
    {
        public void Eat()
        {
            Console.WriteLine("Eating…");
        }
    }

    class Human : Animal//Human類繼承自Animal類
    {
        public void Think()
        {
            Console.WriteLine("Who I am?");
        }
    }

    class Teacher : Human//Teacher了繼承自Human類
    {
        public void Teach()
        {
            Console.WriteLine("I teach programming.");
        }
    }
}

顯式類型轉換

在這裏插入圖片描述

  有可能丟失精度(甚至發生錯誤)的轉換,即cast
  在對象、變量前面加一對()() 裏面寫上要轉換的目標數據類型

			uint x = 65536;
            ushort y = (ushort)x;//uint強制轉換爲ushort
            Console.WriteLine(y);

  使用Convert類進行強制類型轉換

			bool x = true;
            int y = Convert.ToInt32(x);//通過Convert類,將bool轉換爲int
            Console.WriteLine(y);//值爲1

   把數值類型轉換爲字符串類型
  ①使用Convert類的ToString()方法
  ②調用數值數據的實例方法ToString()

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            double x = System.Convert.ToDouble(th1.Text);
            double y = System.Convert.ToDouble(th2.Text);
            double result = x + y;

            //this.th3.Text = System.Convert.ToString(result);//使用Convert類的ToString()方法

            this.th3.Text = result.ToString();//調用數值數據的實例方法ToString()            
        }

  數據類型的Parse/TryParse方法

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            double x = double.Parse(th1.Text);//Parse()只能解析格式正確的字符串數據類型           
            double y = double.Parse(th2.Text);
            double result = x + y;
           
            this.th3.Text = result.ToString();//調用數值數據的實例方法ToString()            
        }

類型轉換操作符是方法的簡記

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            Stone stone = new Stone();
            stone.Age = 5000;
            Monkey wukongSun = (Monkey)stone;//Stone顯式類型轉換爲Monkey類型
            //Monkey wukongSun = stone;//隱式類型轉換
            Console.WriteLine(wukongSun.Age);

        }
    }

    class Stone
    {
        public int Age;

		//public static implicit operator Monkey(Stone stone){…} //隱式類型轉換
		//顯式類型轉換
        public static explicit operator Monkey(Stone stone)//Stone → Monkey 
        {
            Monkey m = new Monkey();
            m.Age = stone.Age / 500;
            return m;
        }
    }

    class Monkey
    {
        public int Age;
    }
}

3.乘法操作符

* 乘法操作符

  要注意“數值提升”。
  具體參見《C# 定義文檔》7.8 算術運算符。

        static void Main(string[] args)
        {           
            var x = 3.0 * 4;//數值提升;int→double
            Console.WriteLine(x.GetType().FullName);//System.Double
            Console.WriteLine(x);//12
        }

/ 除法操作符

    class Program
    {
        static void Main(string[] args)
        {
            //整數的除法;(除數不能爲0)
            int x = 5;
            int y = 4;
            int z = x / y;//整除
            Console.WriteLine(z);//值爲1

            //浮點類型的除法;(正數/0 = ∞ ;負數/0 = -∞)
            double a = 5.0;
            double b = 4.0;
            double c = a / b;
            Console.WriteLine(c);//值爲1.25

            //  ∞ /(-∞) = NaN
            double x1 = double.PositiveInfinity;//正無窮大
            double y1 = double.NegativeInfinity;//負無窮大
            double z1 = x1 / y1;
            Console.WriteLine(z1);//NaN

            double aa = (double)5 / 4;//類型提升; double/int=double
            Console.WriteLine(aa);//值爲1.25 
        }
    } 

% 取餘操作符

    class Program
    {
        static void Main(string[] args)
        {
            //整數的取餘
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine(i % 10);
            }

            //浮點數的取餘
            double x = 3.5;
            double y = 3;
            Console.WriteLine(x % y);//值爲0.5
        }
    }

4.加減操作符

+ 加法操作符

    class Program
    {
        static void Main(string[] args)
        {
            var x = 3.0 + 4;//類型提升
            Console.WriteLine(x.GetType().Name);//Double
            Console.WriteLine(x);

            //連接字符串
            string s1 = "123";
            string s2 = "abc";
            string s3 = s1 + s2;
            Console.WriteLine(s3);//123abc
        }
    } 

- 減法操作符

    class Program
    {
        static void Main(string[] args)
        {
            var x = 3 - 2.0;//類型提升
            Console.WriteLine(x.GetType().Name);//Double
            Console.WriteLine(x);
        }
    } 

5.位移操作符

  數據在內存中的二進制的結構,向左或向右進行一定位數的平移。
  在沒有溢出的情況下,左移就是乘 2 ,右移就是除 2

    class Program
    {
        static void Main(string[] args)
        {
            //左移;最高位補位:都是0
            int x = 7;
            int y = x << 2;//在沒有溢出的情況下,左移:7*2^2
            string strX = Convert.ToString(x, 2).PadLeft(32, '0');
            string strY = Convert.ToString(y, 2).PadLeft(32, '0');
            Console.WriteLine("x的二進制:"+strX);
            Console.WriteLine("y的二進制"+strY+"\r\n");
            Console.WriteLine(y);//值爲28

            //右移;最高位補位:正數補0,負數補1
            int a = 7;
            int b = a >> 2;//在沒有溢出的情況下,右移:/2^2            
        }
    } 

在這裏插入圖片描述

6.關係和類型檢測操作符

< > <= >= 關係操作符

    class Program
    {
        static void Main(string[] args)
        {
            //比較數值大小
            int x = 5;
            double y = 4.0;
            var result = x > y;
            Console.WriteLine(result.GetType().Name);//Boolean
            Console.WriteLine(result);//True


            //比較字符類型—Unicode碼
            char char1 = 'a';
            char char2 = 'A';            
            var result1 = char1 > char2;
            Console.WriteLine(result1);//True

            ushort u1 = (ushort)char1;
            ushort u2 = (ushort)char2;
            Console.WriteLine(u1);//'a'-97
            Console.WriteLine(u2);//'A'-65


            //比較字符串
            string str1 = "abc";
            string str2 = "Abc";
            Console.WriteLine(str1.ToLower() == str2.ToLower());//False 忽略大小寫
           
            int strRes = string.Compare(str1, str2);//0是相等;負值是<;正值是>;
            Console.WriteLine(strRes);
        }
    }   

is as 類型檢測操作符

在這裏插入圖片描述

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            //is操作符:檢驗一個對象是不是某個類型的對象 ∈
            Teacher t = new Teacher();
            var result = t is Teacher;//t是實例new Teacher
            Console.WriteLine(result.GetType().Name);//Boolean
            Console.WriteLine(result);//True

            Teacher t1 = new Teacher();
            var result1 = t1 is Human;//t是實例new Teacher;Teacher類繼承自Human類
            Console.WriteLine(result1.GetType().Name);
            Console.WriteLine(result1);//True

            Car car = new Car();
            Console.WriteLine(car is object);//True

            Human h = new Human();
            var result2 = h is Teacher;
            Console.WriteLine(result2);//False


            //as操作符
            object o = new Teacher();
            if (o is Teacher)//True
            {
                Teacher t2 = (Teacher)o;
                t2.Teach();
            }

            object o1 = new Teacher();
            Teacher tea = o1 as Teacher;
            if (tea != null)
            {
                t.Teach();
            }
        }
    }

    class Animal
    {
        public void Eat()
        {
            Console.WriteLine("Eating…");
        }
    }

    class Human : Animal//Human類繼承自Animal類
    {
        public void Think()
        {
            Console.WriteLine("Who I am?");
        }
    }

    class Teacher : Human//Teacher了繼承自Human類
    {
        public void Teach()
        {
            Console.WriteLine("I teach programming.");
        }
    }

    class Car
    {
        public void Run()
        {
            Console.WriteLine("Running…");
        }
    }
}

7.邏輯與 &| 異或 ^

  一般在操作二進制數據,圖像數據時用。

  按位與:1-true,0-false;真真=真,真假=假,假假=假
  按位或:1-true,0-false;真真=真,真假=真,假假=假
  按位異或:1-true,0-false;真真=假,真假=真,假假=假

    class Program
    {
        static void Main(string[] args)
        {
            //按位與:1-true,0-false;真真=真,真假=假,假假=假
            int x = 7;
            int y = 28;
            int z = x | y;
            string strX = Convert.ToString(x, 2).PadLeft(32, '0');
            string strY = Convert.ToString(y, 2).PadLeft(32, '0');
            string strZ = Convert.ToString(z, 2).PadLeft(32, '0');
            Console.WriteLine(strX);
            Console.WriteLine(strY);
            Console.WriteLine(strZ);


            //按位或:真真=真,真假=真,假假=假

            //按位異或:真真=假,真假=真,假假=假
        }
    }

7.條件與 && 條件或 ||

    class Program
    {
        static void Main(string[] args)
        {
            //條件與
            int x = 5;
            int y = 4;
            int a = 100;
            int b = 200;
            if (x>y && a<b)
            {
                Console.WriteLine("Hello");
            }

            //條件或
            int x1 = 3;
            int y1 = 4;
            int a1 = 100;
            int b1 = 200;
            if (x1 > y1 || a1 < b1)
            {
                Console.WriteLine("Hello");
            }
        }
    }

☆條件與,條件或的短路效應

  儘量避開這種短路效應

  && 左邊爲False,右邊會不執行
  || 左邊已經成立,右邊會不執行

    class Program
    {
        static void Main(string[] args)
        {         
            //條件與,條件或的短路效應
            int x2 = 3;
            int y2 = 4;
            int a2 = 3;
            if (x2>y2 && a2++>3)//&& 左邊爲False,右邊不執行
            {
                Console.WriteLine("Hello");
            }
            Console.WriteLine(a2);//3

            int x3 = 5;
            int y3 = 4;
            int a3 = 3;
            if (x3 > y3 && a3++ > 3)
            {
                Console.WriteLine("Hello");
            }
            Console.WriteLine(a3);//4

            int x4 = 5;
            int y4 = 4;
            int a4 = 3;
            if (x4 > y4 || a4++ > 3)//|| 左邊已經成立,右邊不執行
            {
                Console.WriteLine("Hello");
            }
            Console.WriteLine(a4);//3

            int x5 = 3;
            int y5 = 4;
            int a5 = 3;
            if (x5 > y5 || ++a5 > 3)//|| 左邊不成立,執行右邊
            {
                Console.WriteLine("Hello");
            }
            Console.WriteLine(a5);//4
        }
    }

8.?? null 合併操作符

    class Program
    {
        static void Main(string[] args)
        {
            //可空類型          
            int? x = null; //Nullable<int> x = null;
            x = 100;
            Console.WriteLine(x);//100            


            int? x1 = null;
            int y1 = x1 ?? 1;//如果x是null,賦值1
            Console.WriteLine(y1);
        }
    }

9.?: 條件操作符

    class Program
    {
        static void Main(string[] args)
        {
            int x = 80;
            string str = string.Empty;
            if (x >= 60)
            {
                str = "Pass";
            }
            else
            {
                str = "Failed";
            }
            Console.WriteLine(str);


            //使用條件操作符
            int x1 = 80;
            string str1 = (x1 >= 60) ? "Pass" : "Failed";         
            Console.WriteLine(str1);                      
        }
    }

10.賦值和lambda表達式

    class Program
    {
        static void Main(string[] args)
        {
            int x = 5;
            x += 1;//x = x + 1;
            Console.WriteLine(x);


            int a = 7;
            a <<= 2;//a=a<<2
            Console.WriteLine(a);//7*2*2=28


            int b = 5;
            int c = 6;
            int d = 7;
            int e = b += c *= d;//從右往左:c=c*d=42;b=b+c=47;e=47
        }                             
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章