C#中的get和set访问器可用来获取和设置类中字段(即属性)的值,通过get和set访问器提供访问接口,从而可以避免对字段的直接访问造成的不安全性。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConsoleApplication3
{class Program{static void Main(string[] args){User user = new User(12115789, "兄弟", "余华", 78.5);user.PrintInfo();Console.ReadLine();}}class User{/* ---------------方法1:开始--------------- */private int id; //书本IDprivate string name; //书本名称private string author; //书本作者private double price; //书本价格public int Id{get{return id;}set{id = value;}}public string Name{get{return name;}set{name = value;}}public string Author{get{return author;}set{author = value;}}public double Price{get{return price;}set{price = value;}}/* ---------------方法1:结束--------------- *//* ---------------方法2:开始--------------- *///public int Id { get; set; } //书本ID//public string Name { get; set; } //书本名称//public string Author { get; set; } //书本作者//public double Price { get; set; } //书本价格/* ---------------方法2:结束--------------- *//// <summary>/// 构造函数/// </summary>/// <param name="id"></param>/// <param name="name"></param>/// <param name="price"></param>public User(int id, string name, string author, double price){this.Id = id;this.Name = name;this.Author = author;this.Price = price;}/// <summary>/// 打印书本信息/// </summary>public void PrintInfo(){Console.WriteLine("==================================");Console.WriteLine("书本信息如下:");Console.WriteLine("ID:" + this.Id);Console.WriteLine("名称:" + this.Name);Console.WriteLine("作者:" + this.Author);Console.WriteLine("价格:" + this.Price);Console.WriteLine("==================================");}}
}
方法1使用get和set访问器:
public 数据类型 属性名
{get{return 字段名;}set{字段名 = value;}
}
- get{},get访问器用于获取类中字段的值,需要在get语句中使用return返回一个和字段类型相匹配的值。若希望该属性为只写属性,则在属性的定义中省略get()访问器。
- set{},set访问器用于设置类中字段的值,将程序中传给属性的值赋值给字段。若希望该属性问只读属性,则在属性的定义中省略set()访问器。
方法2使用get和set访问器:
可以再如上代码重看到方法1的用法代码大量重复,因此C#中将属性的设置也可以简化为:
public 数据类型 属性名{ get; set; }
使用方法2定义属性时无需先定义字段,响当于C#中会自动生成一个和属性名相对应的私有字段,这个私有字段对任何类成员都不开放,只能通过定义的属性进行访问,这种属性的定义方式也成为自动属性设置。
- get{},get访问器在自动属性中不能省略,若需要设置为只写属性则需在get前加private进行声明。
- set{},set访问器在自动属性中可以省略,省略后表示该属性为只读属性
当类的成员(包括成员方法和成员函数)是用static声明,访问类的成员时直接使用“类名.类成员”的方式。
当类的成员不是用static声明时,访问类的成员时直接使用“类的对象.类成员”的方式。
需要特别注意的是:若将类中的方法使用static声明为静态方法,则在该方法中只能直接访问使用static声明的成员,非静态成员只能通过类的对象才能访问。