操作符


一.操作符

操作符函数是方法函数的简记法

namespace CreatOperator
{
    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;
        }
    }
}

//两种方法的结果一样

只有圆括号来提高优先级

数组

int[] myIntArray = new int[]{};//[]填数组大小,{}(初始化器)填具体数值

typeof

Type t = typeof(int);
Console.WriteLine(t.Namespace);
Console.WriteLine(t.FullName);
Console.WriteLine(t.Name);
/**
System
System.Int32
Int32
*/

default

获取一个类型的默认值

int x = default(int);
Console.WriteLine(x);
//0
Form myForm = default(Form);
Console.WriteLine(myForm==null);
//true
class Program
{
	static void Main(string[] args)
    {
        Level level = default(Level);
        Console.WriteLine(level);
    }
}
//①
enum Level
{
	Low,
	Mid,
	High
}
//Low

//②
enum Level
{
	Mid,
	Low,
	High
}
//Mid

//③
enum Level
{
	Mid = 1,
	Low = 0,
	High = 2
}
//Low

//④
enum Level
{
	Low = 1,
	Mid = 2,
	High = 3
}
//0

var

声明隐式类型变量

int x = 100;//显式

var y = 100;//隐式	根据赋的值“100”来给y判断类型
Console.WriteLine(y.GetType().Name);
//Int32

new

  • 调用实例构造器

帮助我们在内存当中创建类型的实例

()时表示调用它的实例构造器

如果在new操作符左边有赋值符号的话,那么new操作符会把自己拿到的这个实例的内存地址通过赋值操作符交给负责访问这个实例的变量

Form myForm = new Form();
//myForm为该实例的变量
  • 调用实例的初始化器

花括号{}内可以为这个实例的属性设置它的值,可以通过,来同时设置多个属

Form myForm = new Form(){Text."Hello"};

👆👇

Form myForm = new Form();
myForm.Text = "Hello"; 
  • 一次性访问,没必要创建变量访问实例
new Form(){Text = "Hello"}.ShowDialog();

👆👇

Form myForm = new Form();
myForm.Text = "Hello";
myForm.ShowDialog();
  • 匿名类型创建对象
var person = new{Name = "Mr.Okay", Age = 18};//自动判断类型
Console.WriteLine(person.Age);
Console.WriteLine(person.Name);
Console.WriteLine(person.GetType().Name);
//Mr.Okay
//18
//<>f__AnonymousType0`2
//类型的解释:
//<>f__AnonymousType是约定的一个前缀
//0指的是在程序中创建的第一个
//`2指的是这个类型是一个泛型类,构成这个类型时需要两个类型来构成它,一个是string,一个是int
  • 子类隐藏父类(关键字)(了解即可)

checked&unchecked

检查是否异常

!取非操作符

实际应用,检查

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

    class Student
    {
        public string Name;
        public Student(string initName)
        {
            if(!string.IsNullOrEmpty(initName))
            {
                this.Name = initName;
            }
            else 
            {
                throw new ArgumentException("initName cannot be null or empty");
            }
        }
    }
}

(T)x强制转换类型操作符

二.数据类型转换

convert

string str1 = Console.ReadLine();
string str2 = Console.ReadLine();
int x = Convert.ToInt32(str1);
int y = Convert.ToInt32(str2);
Console.WriteLine(str1 + str2);
Console.WriteLine(x + y);

//12
//34
//1234
//46s

隐式类型转换

  • 不丢失精度的转换
int x = int.MaxValue;
long y = x;
Console.WriteLine(y);

C#语言数据文档6.1.2有隐式数值转换

  • 子类向父类的转换
namespace CreatOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            Teacher t = new Teacher();
            Human h = t;//h仍只有Eat和Animal
            Animal a = h;//访问的是Animal,引用不了实例h,只有Eat
            a.Eat();
        }
    }
	//父类
    class Animal
    {
        public void Eat()
        {
            Console.WriteLine("Eating");
        }
    }
	//子类
    class Human:Animal
    {
        public void Think()
        {
            Console.WriteLine("Who am I?");
        }
    }
	//子类的子类
    class Teacher : Human
    {
        public void Teach()
        {
            Console.WriteLine("I teach programming.");
        }
    }

}
//Eating
  • 装箱

显式类型转换

  • 有可能丢失精度的转换cast(铸造)
Console.WriteLine(ushort.MaxValue);
uint x = 65536;
ushort y = (ushort)x;//强制把较大的值装到小的空间里
Console.WriteLine(y);
  • 拆箱
  • convert
    • 数值类型往字符串类型转换

类型转换操作符

显式类型转换是一个目标类型的实例的构造器,写在被转换的这个数据类型里

namespace CreatOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            Stone stone = new Stone();
            stone.Age = 5000;
            Monkey wukongSun = (Monkey)stone;
            //目标是把一个Stone类型的转变为Monkey类型的
            Console.WriteLine(wukongSun.Age);
        }
    }
    class Stone
    {
        public int Age;
        //显式类型转换是一个目标类型的实例的构造器,写在被转换的这个数据类型里
        //Monkey(Stone stone)就是一个构造器
        public static explicit operator Monkey(Stone stone)
        {
            Monkey m = new Monkey();
            m.Age = stone.Age / 500;//构建Monkey和Stone的关系
            return m;
        }
    }

    class Monkey
    {
        public int Age;
    }
}
//10

对比隐式类型转换

namespace CreatOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            Stone stone = new Stone();
            stone.Age = 5000;
            Monkey wukongSun = stone;		//此处去掉了(Monkey)stone的(Monkey)
            Console.WriteLine(wukongSun.Age);
        }
    }
    class Stone
    {
        public int Age;
        public static implicit operator Monkey(Stone stone)//此处将"explicit"改为"implicit"
        {
            Monkey m = new Monkey();
            m.Age = stone.Age / 500;
            return m;
        }
    }

    class Monkey
    {
        public int Age;
    }
}
//10

is

Stone stone = new Stone();
var result = stone is Stone;//检验的是变量所引用的实例
Console.WriteLine(result.GetType().FullName);
Console.WriteLine(result);

Nullable<>可空类型

例子:一个同学没交作业,但是不是那种做的极差的0分,想给他空着

Nullable<int> x = null;//没交作业
x = 100;//交了作业

👆👇

int?x = null;
x = 100;

但是如果这个同学一直没交作业,期末需要录入成绩时给0分

int?x = null;
int y = x??0;//赋0分

?:(ifelse的简写)

int x = 80;
string str = string.Empty;
str = (x >= 60)?"Pass":"Failed";

👆👇

int x = 80;
string str;
if(x>60)
{
    str = "Pass";
}
else
{
    str = "Failed";
}

文章作者: WB
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 WB !
  目录