C#学习笔记——属性

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

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#编程指南-属性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值