【案例】定义一个猫类Cat,描述猫的以下特征:品种、毛色、体重、出生日期、喵喵叫、抓老鼠。创建并使用这个类的案例。
【案例目的】(1)学会自定义类;
(2)学会自定义类创建、实例化对象,通过对象引用成员。
【代码】如下:
namespace ConsoleApp1 { class Program { static void Main(string[] args) { Cat cat1 = new Cat(); cat1.SetInfo("波斯猫", "白色", 2.3f); cat1.Display(); cat1.Miaow(); Console.WriteLine(); Cat cat2 = new Cat(); cat2.SetInfo("埃及猫", "银色黑斑", 3.1f); cat2.Display(); cat2.CatchMouse(); Console.WriteLine(); Console.ReadLine(); } } //定义一个猫类,描述猫的信息 public class Cat { string variety; string haircolor; float weight; DateTime birthday; public void CatchMouse() { Console.WriteLine("我会抓老鼠!"); } public void Miaow() { Console.WriteLine("喵喵~~!"); } //设置猫各字段值的方法 public void SetInfo(string myVariety, string myHairColor, float myWeight) { variety = myVariety; haircolor = myHairColor; weight = myWeight; birthday = DateTime.Today; } //显示猫信息的方法 public void Display() { //ToShortDateString Console.WriteLine("我是一只{0}\n毛色:{1},重量:{2}千克,生日:{3}", variety, haircolor, weight, birthday.ToShortDateString()); } } }
运行结果如下:
添加属性,并在main()方法中添加对属性的访问。
namespace ConsoleApp1 { class Program { static void Main(string[] args) { Cat cat1 = new Cat(); cat1.SetInfo("波斯猫", "白色", 2.3f); cat1.Display(); cat1.Miaow(); Console.WriteLine(); Cat cat2 = new Cat(); cat2.SetInfo("埃及猫", "银色黑斑", 3.1f); cat2.Display(); cat2.CatchMouse(); Console.WriteLine(); cat1.Weight = 2.7f; Console.WriteLine("cat1的体重变成{0}千克了", cat1.Weight); cat2.HairColor = "黑色"; Console.WriteLine("cat2的毛染成{0}了", cat2.HairColor); Console.ReadLine(); } } //定义一个猫类,描述猫的信息 public class Cat { string variety; string haircolor; float weight; DateTime birthday; public string Variety { set { variety = value; } get { return variety; } } public string HairColor { set { haircolor = value; } get { return haircolor; } } public float Weight { set { weight = value; } get { return weight; } } public void CatchMouse() { Console.WriteLine("我会抓老鼠!"); } public void Miaow() { Console.WriteLine("喵喵~~!"); } //设置猫各字段值的方法 public void SetInfo(string myVariety,string myHairColor,float myWeight) { variety = myVariety; haircolor = myHairColor; weight = myWeight; birthday = DateTime.Today; } //显示猫信息的方法 public void Display() { //ToShortDateString设置日期格式 Console.WriteLine("我是一只{0}\n毛色:{1},重量:{2}千克,生日:{3}", variety, haircolor, weight, birthday.ToShortDateString()); } }
}
运行结果如下: