属性有四个种类:可读属性(需实现get和set访问器)、只读属性(实现get访问器)、只写属性(实现set访问器)和Static属性(只能访问静态数据)参考下面这个例子:
//这个例子是在vs2008中实现的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace shuxing
{
class program
{
static void Main()
{
User zs = new User();
User ls = new User();
zs.Name = "张三";
zs.Sex = "女";
zs.Birthday = Convert.ToDateTime("1980-1-1");
Console.WriteLine(User.LoginCount);
Console.WriteLine("姓名:" + zs.Name + " 性别:" + zs.Sex+ " 年龄:"+zs.Age);
}
}
class User
{
private string m_Name;
private string m_Sex;
private DateTime m_Birthday;
private static int m_LoginCount;
public User()
{
m_LoginCount++;
}
public static int LoginCount //静态只读属性
{
get
{
return m_LoginCount;
}
}
public DateTime Birthday //只写属性
{
set
{
if (value < Convert.ToDateTime("1900-1-1") || value.Year > DateTime.Now.Year - 3)
Console.WriteLine("用户年龄非法");
else
{
m_Birthday = value;
}
}
}
public int Age //只读属性
{
get
{
return DateTime.Now.Year - m_Birthday.Year;
}
}
public string Name //读写属性
{
get
{
return m_Name;
}
set
{
m_Name = value;
}
}
public string Sex //读写属性
{
get
{
return m_Sex;
}
set
{
if (value == "男" || value == "女")
{
m_Sex = value;
}
else
{
Console.WriteLine("性别只能为“男”或“女”");
}
}
}
}
}
注:上面这个例子使用了属性,使代码更加清晰还逻辑严密。