C#:字段与属性

MSDN中是这么介绍字段和属性的:

A field is a variable of any type that is declared directly in a class or struct.

字段:“字段”是直接在结构中声明的任何类型的变量。

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field.Properties can be used as if they are public data members, but they are actually special methods called accessors.This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

属性是这样的成员:它们提供灵活的机制来读取、编写或计算私有字段的值。可以像使用公共数据成员一样使用属性,但实际上它们是称为“访问器”的特殊方法。这使得数据在可被轻松访问的同时,仍能提供方法的安全性和灵活性。

字段是变量,而属性是方法。字段一般是private的,而属性一般是public的。外部代码可以通过属性来访问字段,实现对字段的读写操作,所以属性又称访问器。

属性可以控制外部代码对字段的访问权限:通过只实现get访问器,使字段是只读的;通过只实现set访问器使字段是只写的;同时实现get和set访问器,则外部可对该字段进行读写操作。

①属性同时包含 get 和 set 访问器,允许任何对象读写该属性。相应的任何对象也可以对该属性所对应的字段进行读写操作。

 1     public class Person
 2     {
 3         //-----------------------
 4         //可读可写
 5         //-----------------------
 6         private string name;
 7         /// <summary>姓名</summary>
 8         public string Name
 9         {
10             get
11             {
12                 return this.name;
13             }
14             set
15             {
16                 this.name = value;
17             }
18         }
19     }

 ②属性只包含get访问器,省略set访问器,则该属性为只读的。相应的外部代码只能对该属性所对应的字段进行读操作。

 1     public class Person
 2     {
 3         //-----------------------
 4         //只读
 5         //-----------------------
 6         private string name;
 7         /// <summary>姓名</summary>
 8         public string Name
 9         {
10             get
11             {
12                 return this.name;
13             }
14         }
15     }

 ③属性只包含set访问器,省略get访问器,则该属性为只写的。相应的外部代码只能对该属性所对应的字段进行写操作

 1     public class Person
 2     {
 3         //-----------------------
 4         //只写
 5         //-----------------------
 6         private string name;
 7         /// <summary>姓名</summary>
 8         public string Name
 9         {
10             set
11             {
12                  this.name=value;
13             }
14         }
15     }

 属性可以对字段的写操作进行有效性验证。

 1     public class Person
 2     {
 3         //-----------------------
 4         //有效性验证
 5         //-----------------------
 6         private int age;
 7         /// <summary>年龄</summary>
 8         public int Age
 9         {
10             get
11             {
12                 return this.age;
13             }
14             set
15             {
16                 if (value <= 0 || value >= 150)
17                 {
18                     throw new ArgumentOutOfRangeException("Age", "The range of age is between 1 and 150.");
19                 }
20             }
21         }
22     }
原文地址:https://www.cnblogs.com/PolarisSky/p/3864109.html