c#编码技巧(八):属性的多种写法及用途举例

写法及用途看注释:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simplifiy
{
    public class Person
    {
        //1.全写
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        //2.全简写
        public int Age { get; set; }

        //3.半简写
        private string address;
        public string Address => address;  //等价于 public int Age { get { return age; } }

        //4.只读,不可写入
        public float Money { get; }
        public float PrivateMoney { get; private set; }

        //5.get set有代码的简写
        //属性的用途之一:此处体现了属性的好处,用get给属性赋初值,set赋值可省去一个SetIntroduction()方法,使代码更简洁
        private string introduction;
        public string Introduction
        {
            get => string.Format($"{introduction}My name is {name}, I am {Age} years old");
            set => introduction = string.Format($"Hello {value}, ");
        }

        //等价于
        //public string Introduction
        //{
        //    get
        //    {
        //        return string.Format($"{introduction}My name is {name}, I am {Age} years old");
        //    }
        //    set 
        //    {
        //        introduction = string.Format($"Hello {value}, ");
        //    }

        //}

        //C# 9.0(.NET5)语法
        public int Number { get; init; } //init: 只能在对象的构造阶段赋值,即在对象或它的子类的构造函数中赋值,赋值后不允许第二次修改

        #region 如果定义了一个内部字段,想提供public给外部访问,只允许构造初始化时赋值,不允许第二次赋值,则可以这样写
        private readonly string _numberId;
        public string NumberId
        { 
            get => _numberId; 
            init => _numberId = (value ?? throw new Exception(nameof(NumberId)));
        }
        public Person(string numberId)
        {
            NumberId = numberId;
        }
        #endregion

    }
    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person();
            person.Name = "Tom";
            person.Age = 18;
            //person.Address = "Shenzhen"; // 语法错误
            //person.Money = 100.0;// 语法错误
            //person.PrivateMoney = 1000.0// 语法错误

            Console.WriteLine(person.Introduction);//输出:My name is Tom, I am 18 years old
            
            person.Introduction = "Sofia";
            Console.WriteLine(person.Introduction);//输出:Hello Sofia, My name is Tom, I am 18 years old
            Console.ReadLine();
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值