1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace Ch1_Name 7 { 8 public class Name 9 { 10 private string fname, mname, lname; 11 public Name(string first, string middle, string last) 12 { 13 fname = first; 14 mname = middle; 15 lname = last; 16 } 17 public string firstName 18 { 19 get { return fname; } 20 //set { fname = firstName; } 21 } 22 public string middleName 23 { 24 get { return mname; } 25 //set { mname = middleName; } 26 } 27 public string lastName 28 { 29 get { return lname; } 30 //set { lname = lastName; } 31 } 32 public override string tostring() 33 { 34 return string.Format("{0}{1}{2}", fname, mname, lname); 35 } 36 public string initials() 37 { 38 return string.Format("{0}{1}{2}", fname.Substring(0, 1), mname.Substring(0, 1), lname.Substring(0, 1)); 39 } 40 } 41 42 class Program 43 { 44 static void Main(string[] args) 45 { 46 Name myName = new Name("App","Ban","Code"); 47 string fullName, inits; 48 fullName = myName.ToString(); 49 inits = myName.initials(); 50 Console.WriteLine("My name is {0}", fullName); 51 Console.WriteLine("My initials are {0}", inits); 52 } 53 } 54 }
重点说说get和set的用法。
以我的观点来看,get和set就是为了取代以前C++里的如下用法:
public class CClass { private int num; public int getNum() { return num; } public void setNum(int newNum) { num = newNum; } }
和以前的写法主要区别在于,C++采用公用成员函数的方法操作private数据,而C#采用与private数据相同格式的public数据,并在public数据上定义get和set。