(5)C#运算符

一、运算符

参照javase     (7)java基础知识-原码、反码、补码、运算符

二、运算符2

1. checked unchecked 运算符

   1.1checked 当变量溢出时不再默默溢出,而是抛出异常

            int a = 1000000;
            int b = 1000000;
            int c = a * b;//-727379968
            int d = checked(a * b);// 抛异常 System.OverflowException:“Arithmetic operation resulted in an overflow.”
            Console.WriteLine(c);

checked  1.对double和float没作用,他们溢出为特殊无限值。2.对decimal类型也没作用这种类型总是进行溢出检查

  1.2 unchecked 

不进行溢出检查

 

2.is运算符

 检查is左边对象是否可转换的为is右边的类型。可以则返回true

该运算符常在向下类型转换前使用,不能用于自定义类型和数值转换

    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            if ( p is object) Console.WriteLine("True"); 
        }
    }

C#7新增功能 

右边类型可以定义一个变量,该变量是左边变量转换为右边以后的类型实例

    class Program
    {
        static void Main(string[] args)
        {
            Dog dog = new Dog();
            if (dog is Animal animal) animal.add(); //等价于 ((Animal)dog).add()//打印Dog
        }
    }

  public  class Animal {virtual public void add() { Console.WriteLine("Animal"); } }
  public class Dog:Animal { override public void add() { Console.WriteLine("Dog"); } }

3.as运算符  -C#6新增

 as运算符在向下类型转换出错时会返回null

        static void Main(string[] args)
        {
            object o1 = "abc";
            object o2 = 3;
            string str1 = o1 as string;
            Console.WriteLine("str1: "+str1);
            string str2 = o2 as string;
            if (str2 == null) { Console.WriteLine("str2: " + "null"); }

            //string str3 = (string)o2;//抛异常  System.InvalidCastException:“Unable to cast object of type 'System.Int32' to type 'System.String'.”
        }

4.sizeof运算符

5.type运算符

6.nameof运算符

    class Program
    {
        static void Main(string[] args)
        {
           string str= nameof(Program.ToString);
           Console.WriteLine(str);//ToString
        }
    }

7.index运算符

8.可空类型运算符

 给不能为空的类型赋值为空

int? a = null;//

9.空合并运算符

  如果??左边为空,则执行右边

    class Program
    {
        static void Main(string[] args)
        {
            int? a = null;//
            Console.WriteLine(a);
            int? b = a ?? 10;
            Console.WriteLine(b);
            Console.ReadLine();
        }
    }

10.空条件运算符

 如果变量为空时表达式不会抛出空异常,而是赋值给变量为null

            string s = null;
            //string str = s.ToString(); //报空异常 System.NullReferenceException:“Object reference not set to an instance of an object.”
            string str2 = s?.ToString();
            if(str2==null) Console.WriteLine("null");
            Console.ReadLine();

三、运算符重载

四、自定义索引运算符

原文地址:https://www.cnblogs.com/buchizaodian/p/5600311.html