第六节 操作符详解
视频链接:刘铁猛老师的《C#语言入门详解》
https://www.youtube.com/watch?v=EgIbwCnQ680&list=PLZX6sKChTg8GQxnABqxYGX2zLs4Hfa4Ca
操作符概览#
操作符的本质#
class Program{ static void Main(string[] args){ int x=3; int y=4; int z=x/y; Console.WriteLine(z);// 0 double a=3.0; double b=4.0; double c=a/b; Console.WriteLine(c);// 0.75 } }
自定义操作符运算 运算符重载#
// 正常定义方法 internal class Program { static void Main(string[] args) { Person farther = new Person(); farther.Name = "father"; Person momther = new Person(); momther.Name = "momther"; List<Person> home = Person.GetMarray(farther, momther); foreach (Person homeItem in home) { Console.WriteLine(homeItem.Name); } } } class Person { public string Name; public static List<Person> GetMarray(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 = "child" + i.ToString(); people.Add(child); } return people; } } // 自定义运算符操作 internal class Program { static void Main(string[] args) { Person farther = new Person(); farther.Name = "father"; Person momther = new Person(); momther.Name = "momther"; List<Person> home = farther + momther; foreach (Person homeItem in home) { Console.WriteLine(homeItem.Name); } } } class Person { public string Name; 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 = "child" + i.ToString(); people.Add(child); } return people; } } // 二者运行结果都一样
优先级与运算顺序#
基本操作符、关键字的作用#
typeof#
- 查看某个类型的元数据(记录关于这个类的命名空间,名称,父名称,方法名称个数等信息)
default#
new#
-
在内存中帮助我们创建一个内存中的实例,并且立刻调用这个实例的实例构造器 new Form();
-
还可以把该实例的内存位置 告诉通过赋值符号 交给引用这个实例的引用变量 Form f=new Form();
-
给匿名类型创建对象 var person= new {Name="Mr.Wang",Age=20}; {}是初始化构造器
-
new 作为关键字使用,这里的作用是将父类的Report方法给隐藏了
checked和unchecked#
delegate作为操作符使用(已被lambda表达式取代)#
sizeof#
- 获得一个对象在内存中所占用的字节数(一个字节8位)
- 默认情况下,只能是基本数据类型,排除string和object,也就是结构体型的基本数据类型
- 非默认情况下,可以去获取自定义的结构体性的数据类型,但是需要放到不安全的上下文中
- 注意这里要使用unsafe,还需要在vs上设置
- 并且这里x打印的大小不是4+8=12,还是16(高级部分)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构