namespace NameSpace1 {
public partial class MyClass : System.Web.UI.Page
{
private int age = 5;
protected string name = "xiaoMing";
protected string Location {get; set;}
protected void Page_Load(object sender, EventArgs e)
{ Location = "beijing";
}
}
}
个人的理解,应该用属性。即protected string Location {get; set;},不用 protected strng Location = "beijing"。
目前的理由:
1,protected string location = "beijing"会被默认构造函数初始化为string location = ""然后再赋值location = "beijing"。
而属性只被初始化一次,例如调用Set方法Location = "beijing";
2,属性体现了封装。可以添加判断,限制Location被随意地改变。
本文深入探讨了C#中属性的使用及其在实现类成员封装时的作用,详细解释了属性与直接赋值的区别,以及如何通过属性实现类成员的封装和控制。
304

被折叠的 条评论
为什么被折叠?



