C# 字段与属性
1:C# 为什么有了字段还要属性呢?
在某些方面我们需要限制字段赋值的范围,或者是只读或者只写,这些单靠字段是无法实现的因此有了属性。
代码如下:
public class Person { private Person() { } static Person() { Current = new Person(); } public static Person Current; public int Age; //字段 public void ShowPerson(string Name) { Console.WriteLine("{0}的年龄为:{1}", Name, Age); } } //调用如下 // 由于字段是公开的无法对数据进行非法校验。 Person.Current.Age = 130; Person.Current.ShowPerson("小明"); Console.ReadKey();
属性: 因为属性有set,get 方法可以对其进行安全校验,很好避免数据赋值超限,可以保证数据安全性
public class Person { private Person() { } static Person() { Current = new Person(); } public static Person Current; private int age; public int Age { set { if (value == 0 && value <= 100) this.age = value; else throw new Exception("值的范围不合法。"); } get { return this.age; } } public void ShowPerson(string Name) { Console.WriteLine("{0}的年龄为:{1}", Name, Age); } }

浙公网安备 33010602011771号