19.属性(2)

get获取属性值 set设置属性值

 

代码
namespace _19.属性_2_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
User zs
= new User();
zs.Birthday
= Convert.ToDateTime("1999-1-1");
MessageBox.Show(
"年龄:" + zs.Age);

}
}
class User
{
private DateTime m_Birthday;
public DateTime Birthday//只写属性
{
set
{
if (value < Convert.ToDateTime("1900-1-1") || value.Year > DateTime.Now.Year-3)
MessageBox.Show(
"wrong!");
else
m_Birthday
=value ;
}
}
public int Age//只读属性
{
get
{
return DateTime.Now.Year - m_Birthday.Year;
}
}
}
}

在类里面声明一个计数器,用来记录网站被访问的次数(显示“4”)

代码
namespace _19.属性_2_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
User zs
= new User();
User w1
= new User();
User w2
= new User();
User e3
= new User();
MessageBox.Show(User.LoginCount
+"");

}
}
class User
{
private static int m_LoginCount;
public User()
{
m_LoginCount
++;
}
public static int LoginCount //静态只读属性
{
get
{
return m_LoginCount;
}
}
}
}

 

 

 

posted @ 2010-03-11 17:18  平凡人生  阅读(156)  评论(0编辑  收藏  举报