码迷,mamicode.com
首页 > 其他好文 > 详细

C#:字段与属性

时间:2014-07-24 04:58:08      阅读:290      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   使用   

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;set;
11         }
12     } 

 ②属性只包含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     }

 ③属性只包含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     }

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

 1         //-----------------------
 2         //有效性验证
 3         //-----------------------
 4         private int age;
 5         /// <summary>年龄</summary>
 6         public int Age
 7         {
 8             get;
 9             set {
10                 if (value <= 0 || value >= 150)
11                 {
12                     throw new ArgumentOutOfRangeException("Age", "The range of age is between 1 and 150.");
13                 }
14             }
15         }

C#:字段与属性,布布扣,bubuko.com

C#:字段与属性

标签:des   style   blog   http   color   使用   

原文地址:http://www.cnblogs.com/PolarisSky/p/3864109.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!