using System; namespace test { class Program { static void Main(string[] args) { Cat kitty = new Cat(); // 無參構造函數 Cat1 KITTY = new Cat1("KITTY", 4); C ...
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; } } } }