c# 第五章 类 方法与重载

class

using aaaa; using System; using System.Collections.Generic; using System.Text; namespace aaaa { class Car { private string color;//不建议这样写,建议开头改为大写 public string Color { get { return color; } set { color = value; } //赋值时自动调用set //读取时自动调用get } public string sds { get; get; } = "白色"; //自动属性 //编译器自动生成私有字段 //无需手写字段和访问器体 } }
//35 //字段:是类的数据成员,用来访问数据 //访问修饰符 类型 字段名;不写默认private /* * class a * { * public:int a; * private :string b; * } */ //36 //属性 using aaaa; Car car1 = new Car(); car1.Color = "sjshks";//调用set string c = car1.Color;//调用get
using System.Text; //方法:类似c++的成员函数,但是前面要加访问的权限,同样也可以进行重载 namespace aaaa { class Car { public string Colour { get; set; } public void Start() { Console.WriteLine("ok"); } } } 样例
using System; public class Book { private string tittle; private string author; private double price; private int year; public Book() { tittle = "未知"; author = "未知"; price = 0; year = 0; } public Book(string tittle,string author,double price,int year) { this.tittle = tittle; this.author = author; this.price = price; this.year = year; } public string Tittle { get { return tittle; } set { tittle = value; } } public string Author { get { return author; } set { author = value; } } public double Price { get { return price; } set { price = value; } } public int Year { get { return year; } set { year = value; } } public void ShowInfo() { Console.WriteLine($"书名:{tittle}"); Console.WriteLine($"作者:{author}"); Console.WriteLine($"价格:{price}"); Console.WriteLine($"出版年月:{year}"); } public bool isNewBook() { int currentYear = DateTime.Now.Year; return (currentYear - year) <= 5; } public string GetInfo() { return $"《{tittle}》-{author}-{price:C}-{year}年"; } }

主执行

Book book1 = new Book(); book1.Tittle = "C# 编程指南"; book1.Author = "张三"; book1.Price = 59.9; book1.Year = 2024; book1.ShowInfo();