Home  >  Article  >  类库下载  >  C# property accessor

C# property accessor

高洛峰
高洛峰Original
2016-10-13 16:31:511542browse

A property's accessor contains executable statements related to getting or setting the property. An accessor declaration can contain a get accessor, a set accessor, or both. The declaration takes one of the following forms:

get {}
set {}

get accessor:
get The accessor body is similar to the method body. It must return a value of the property type. Executing the get accessor is equivalent to reading the value of the field.

The following is the get accessor that returns the value of the private field name:

private string name;  // the name field
 
public string Name  // the Name 
 
property
{    
   get
   {       
       return name;
   }
}

When a property is referenced, the get accessor will be called to read the value of the property unless the property is the target of assignment.

Example:

Employee e1 = new Employee();
 ...
 Console.Write(e1.Name); // The get accessor is invoked here

get accessor must be terminated in a return or throw statement, and control cannot extend beyond the accessor body.



set accessor:
set accessor is similar to a method that returns void. It takes an implicit parameter called value, the type of this parameter is the type of the property.

In the following example, a set accessor is added to the Name property:

public string Name
{  
   get
   {  
        return name;
   }  
     
   set
   {
       name = value;
   }
}

When a value is assigned to a property, the operation calls the set accessor.

For example:

e1.Name = "Joe"; // The set accessor is invoked here

It is an error to use implicit parameter names (value) for local variable declarations in the set accessor.


Remarks:

Properties are classified according to the accessor used as follows:
Properties with only get accessor are called read-only properties. Cannot assign a value to a read-only property.
Properties with only set accessors are called write-only properties. A write-only property cannot be referenced except as the target of an assignment.
Properties with both get and set accessors are read-write properties.
In property declaration, both get and set accessors must be declared inside the property body.
Using the get accessor to change the state of an object is a bad programming style.


We use the following example to understand what an accessor is:

 using System; 
 namespace AccessorEG
 {     
     public class Student
     {         
         // 私有字段 private field
         private int _age; 
          
         // 公开的属性 public property
         public int Age
         {             
            get { return _age; }             
            set { _age = value; }
         }
     } 
      
     class Program
     {         
         static void Main(string[] args)
         {
             Student stu = new Student();
             stu.Age = 10;                           // 使用了修改
             Console.WriteLine(stu.Age.ToString()); //使用了读取 输出 10                  
             Console.ReadKey();                    
         }
     }
 }

It is easy to understand that an accessor refers to the interface of an object type member to the outside world, and is a bridge that allows object type members to interact with the outside world. With the accessor, the outside world can perform corresponding operations of reading and writing on the object members.

So, what members can have accessors? Accessors can be declared for non-read-only fields and events. Of course, the read-only domain can also provide an interface that can be obtained by the outside world, that is, get, but it can only be initialized in the declaration or constructor, and it does not support the set method.

 using System; 
 namespace AccessorEG
 {     
     public class Student
     {         
         // 私有字段 private field
         private readonly int _age = 10; 
          
         // 公开的属性 public property
         public int Age
         {   
               get { return _age; }
         }
     } 
      
     class Program
     {        
         static void Main(string[] args)
         {
             Student stu = new Student();
             Console.WriteLine(stu.Age.ToString());  // 使用了读取   输出 10                
             Console.ReadKey();                              
         }
     }
 }

The value of the read-only field in the above code has been assigned when it is declared, and the set method cannot be provided in the accessor corresponding to the public property, otherwise it will not be compiled, but it can be obtained by the outside world.

We have something to say about the accessors of fields. The common ones are as follows:

using System; 
 namespace AccessorEG
 {     
     public class Student
     {         
         #region 全访问权限         // 私有字段
         private int _age;        // 与_age对应的公开属性,包含了set和get方法
          
         public int Age
         {             
             get { return _age; }             
             set { _age = value; }
         } 
         // 如果您安装了.NET3.0,那么您可以使用自动属性,届时,上面的代码即可以下面的代替
      // 在VS.NET下输入 prop 连击两下Tab键,编译器会自动帮您生成自动属性
      // public int Age { get; set; }
         #endregion // 全访问权限
  
         #region 只读属性         
         private string _name; 
          
         public string Name
         {             
            get { return _name; }
         } 
         // 等同于
      // public string Name { private set; get; }
         #endregion
  
         #region 只写属性         
         private bool _sex; 
          
         public bool Sex
         {          
             set { _sex = value; }
         }         
         // 等同于
      // public bool Sex { set; private get; }
         #endregion
  
     } 
      
     class Program
     {         
         static void Main(string[] args)
         {
             Student stu = new Student();
             stu.Age = 18;             
             // stu.Name = "Johness"; 异常,编译错误,因为该属性只读
         // Console.WriteLine(stu.Sex.ToString()); 异常,编译错误,因为该属性只写
             Console.WriteLine(stu.Age.ToString());  // 使用了读取                    Console.ReadKey();             // 输出 18         
         }
     }
 }

The read-only and write-only in the above examples are only valid for the outside world. If you explicitly specify the owner of the accessor, that is Private fields of the class. Then inside the class, you can still conveniently use the private fields you defined for read and write operations. Therefore, I recommend that friends define fields and their accessors using the syntax of .NET 2.0 instead of the new syntax of 3.0 (automatic attributes ). Of course, accessors can also be used to better verify data validity:

using System; 
 namespace AccessorEG
 {     
     public class Student
     {         
         // 私有字段
         private int _age;  // 与_age对应的公开属性,包含了set和get方法
          
         public int Age
         {             
             get { return _age; } // 利用访问器对输入的年龄进行验证
         // 如果输入值小于0或者大于100
         // 可以赋为默认值18或者不进行操作
             set 
             {                 
                   if (value >= 0 && value <= 100)
                    _age = value;   // 如果数据无效不进行操作可以注释以下内容
                   else
                    _age = 18;
             }
         }
  
     } 
      
     class Program
     {         
         static void Main(string[] args)
         {
             Student stu = new Student();
             stu.Age = -2;   // 赋无效值                     
             Console.WriteLine(stu.Age.ToString()); 
             Console.ReadKey();    // 输出 18         
         }
     }
 }


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more