0103-面向对象类的特性
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace _02面向对象 { class Program { static void Main(string[] args) { Person p=new Student(); p.Age = -20; Console.WriteLine(p.Age); //年龄-20读取是会被属性保护输出为18 p.SayHello(); //输出:我是人类 Student s=((Student)p); s.SayHello();//输出:我是学生 s.SecName = "女超人"; s.Test(); //创建教师对象实例 Teacher th=new Teacher("阿程",28,'男',89,96,98); th.SayHi();//我叫阿程,我是男生,今年28岁 th.ShowScore(); //我叫阿程,总成绩283,平均分94 Teacher t = new Teacher("春老师", 18, '女'); t.SayHi(); Console.ReadKey(); } } /* //面向对象的三大特性:封装、继承、多态 new 创建对象:1、在堆中开辟内存空间 2、在堆中创建对象 3、调用对象的构造函数 this 1、代表当前类的对象 2、显式的调用自己的构造函数 base 1、调用父类的成员,包括调用父类的构造函数 字段:存储数据 属性:保护字段 函数:描述对象的行为 构造函数:初始化对象,给对象的属性进行赋值 */ class Person { private string _name; private int _age; public string Name { get { return _name; } set { _name = value; } } public int Age { get //属性值保护 { if (_age <= 0 || _age > 160) { return _age = 18; } return _age; } set { _age = value; } } public char Gender { get; set; } public void SayHello() { Console.WriteLine("我是人类"); } } class Student:Person { public string SecName { get; set; } public new void SayHello() //使用new关键字可以隐藏父类方法 { Console.WriteLine("我是学生"); } public void Test() { string SecName; SecName = "弹力女超人"; Console.WriteLine("{0}",SecName); //局部变量 Console.WriteLine("{0}",this.SecName); //成员变量 } } class Teacher:Person { public int Chinese { get; set; } public int Math { get; set; } public int English { get; set; } public Teacher(string name,int age,char gender,int chinese,int math,int english) { this.Name = name; this.Age = age; this.Gender = gender; this.Chinese = chinese; this.English = english; this.Math = math; } //以下两个构造方法通过this关键字调用本身的全参的构造方法 public Teacher(string name,int age,char gender):this(name,age,gender,0,0,0) { } public Teacher(string name, int chinese, int math, int english) : this(name, 0, '\0', chinese, math, english) { } public void SayHi() { Console.WriteLine("我叫{0},我是{1}生,今年{2}岁",this.Name,this.Gender,this.Age); } public void ShowScore() { Console.WriteLine("我叫{0},总成绩{1},平均分{2}",this.Name, this.Chinese+this.Math+this.English,(this.Chinese + this.Math + this.English)/3); } } }
凡哥,别他妈吹牛逼了
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)