C#学习笔记——属性

来源:互联网 发布:淘宝达人等级v2怎么升 编辑:程序博客网 时间:2024/06/04 23:33

  属性是一种成员,它提供灵活的机制来读取、写入或计算私有字段的值。 属性可用作公共数据成员,但它们实际上是称为访问器的特殊方法。 这使得可以轻松访问数据,还有助于提高方法的安全性和灵活性。

get属性访问器用于返回属性值;set属性访问器用于分配新值。
value关键字用于定义由set分配的值。

//表示时间间隔的类class TimePeriod{//将时间间隔以秒为单位存到seconds中   private double seconds;/*允许客户以小时为单位指定时间间隔。 get 和 set 访问器都会执行小时与秒之间的必要转换。 此外,set 访问器还会验证数据,如果小时数无效,则引发 @System.ArgumentOutOfRangeException。*/   public double Hours   {       get { return seconds / 3600; }       set {           if (value < 0 || value > 24)             throw new ArgumentOutOfRangeException(                   $"{nameof(value)} must be between 0 and 24.");          seconds = value * 3600;        }   }}class Program{   static void Main()   {       TimePeriod t = new TimePeriod();       //调用set       t.Hours = 24;       //调用get       Console.WriteLine($"Time in hours: {t.Hours}");   }}

只读的属性,将 get 访问器作为 expression-bodied 成员实现:

using System;public class Person{   private string firstName;   private string lastName;   public Person(string first, string last)   {      firstName = first;      lastName = last;   }//Name为只读属性   public string Name => $"{firstName} {lastName}";   }public class Example{   public static void Main()   {      var person = new Person("Isabelle", "Butts");      Console.WriteLine(person.Name);   }}

get 和 set 访问器都可以作为 expression-bodied 成员实现:

public class SaleItem{   string name;   decimal cost;   public SaleItem(string name, decimal cost)   {      this.name = name;      this.cost = cost;   }   public string Name    {      get => name;      set => name = value;   }   public decimal Price   {      get => cost;      set => cost = value;    }}class Program{   static void Main(string[] args)   {      var item = new SaleItem("Shoes", 19.95m);      Console.WriteLine($"{item.Name}: sells for {item.Price:C2}");   }}

自动实现的属性:

public class SaleItem{   public string Name    { get; set; }   public decimal Price   { get; set; }}class Program{   static void Main(string[] args)   {      var item = new SaleItem{ Name = "Shoes", Price = 19.95m };      Console.WriteLine($"{item.Name}: sells for {item.Price:C2}");   }}

参考资料:
Microsoft文档-C#编程指南-属性

原创粉丝点击