C#类的成员分为两种类型,如下表所示
数据成员分组为实例成员和静态成员
1、实例成员,默认情况下,所有成员都是实例成员,除非他们是常理或者有前缀static关键字,如
public int ID;
public string FirstName;
public string LastName;
public string Email;
只能通过类的实例访问实例成员
,并且类的每个实例(对象)都有自己的数据副本,如
- public class Contact
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public string City { get; set; }
- }
- Contact c1 = new Contact();
- c1.ID = 10;
- c1.Name = "China";
- c1.City = "Hefei";
- Contact c2 = new Contact();
- c2.ID = 100;
- c2.Name = "America";
- c2.City = "NewYork";
- string s1 = string.Format("c1.ID={0},c1.Name={1},c1.City={2}", c1.ID, c1.Name, c1.City);
- string s2 = string.Format("c2.ID={0},c2.Name={1},c2.City={2}", c2.ID, c2.Name, c2.City);
- MessageBox.Show(s1 + "\n\r" + s2);
输出:
2、静态成员
静态数据成员属于类,而不是属于类的每个实例
,使用static关键定义静态成员,如:
- public class Contact
- {
- <span style="white-space:pre"> </span> public static int count;
- public int ID { get; set; }
- public string Name { get; set; }
- public string City { get; set; }
- }
不可以通过类的实例来访问count,需要通过类访问该变量,如:Contact.count=4;