using System; namespace test { class Program { static void Main(string[] args) { Cat kitty = new Cat(); // 无参构造函数 Cat1 KITTY = new Cat1("KITTY", 4); Cat1 KITTY1 = new Cat1(); /*kitty.Setage(-3);访问器操作 kitty.Name = "Kitty"; Console.WriteLine("大家好,我叫{0},今年{1}岁了",kitty.Name,kitty.Getage());*/ kitty.Name = "Kitty"; kitty.age = 3; Console.WriteLine("大家好,我叫{0},今年{1}岁了", kitty.Name, kitty.age);//无参构造函数,age用了属性方法 Console.WriteLine("大家好,我叫{0},今年{1}岁了", KITTY.na, KITTY.ag);//有参构造函数 Console.WriteLine("大家好,我叫{0},今年{1}岁了", KITTY1.na, KITTY1.ag);//无参构造函数 kitty.CatchMouse(); kitty.CatchMouse(); } } class Cat { public string Name;//字段 private int Age; private int NO = 0;//私有的 /* public void Setage(int age)//与下面Getage合起来叫做访问器 { if (age < 0) { Age = 0; } else { Age = age; } } public int Getage() { return Age; }与上面Setage合起来叫做访问器,Java用的比较多*/ //C#里的属性方法 public int age { set { if (value < 0) { Age = 0; } else { Age = value; } } get { return Age; } } private void Hello()//方法 介绍自己 { Console.WriteLine("你们好啊,我是{0}.", Name); } public void call()//叫声 { Hello(); Console.WriteLine("喵喵。。。。"); } public void CatchMouse()//行为 { this.NO++; Console.WriteLine("我抓了{0}只老鼠.", NO); } } class Cat1 { private string name1; private int age1; public Cat1()//显示说明构造函数 { } /// <summary> /// 弄成和类名一样的有参构造函数 /// </summary> /// <param name="namevalue"></param> /// <param name="agevalue"></param> public Cat1(string name1value, int age1value) { name1 = name1value; age1 = age1value; } public string na { set { name1 = value; } get { return name1; } } public int ag { set { age1 = value; } get { return age1; } } } }