【一起学习C#】类的字段和属性

  • 字段就是变量,用来储存数据
        //字段
        string _id;
        string _name;

如上,_id用来保存学号,_name用来保存姓名。

  • 属性有set和get块,分别对应写和读,二者至少存在一个。
        //属性
       public string Id
        {
            get
            {
                return _id;
            }
            set
            {
                _id = value;
            }
        }

如何快速的添加属性?

1.右击字段,选择快速操作和重构右击字段,选择快速操作和重构
2.选择封装字段(并使用属性) 选择封装字段(并使用属性)
快速添加的属性如下:

 public string Name { get => _name; set => _name = value; }

完整的代码如下:

//Student.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test1
{
    class Student
    {
        //字段
        string _id;//学号
        string _name;//姓名
        bool _sex;//性别
        DateTime _birth;//出生日期
        
        //属性
        public string Id
        {
            get
            {
                return _id;
            }
            set
            {
                _id = value;
            }
        }
        public string Name { get => _name; set => _name = value; }
        public DateTime Birth { get => _birth; set => _birth = value; }
        public bool Sex { get => _sex; set => _sex = value; }
        public int Age
        {
            get
            {
                return DateTime.Now.Year - Birth.Year;
            }
        }
    }
}

//Program.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test1
{
    class Program
    {
        static void Main(string[] args)
        {
            Student lzw = new Student();
            lzw.Id = "182056218";
            lzw.Name = "梁志文";
            lzw.Sex = true;
            lzw.Birth = new DateTime(2000, 11, 10);
            Console.WriteLine("学号:{0}", lzw.Id);
            Console.WriteLine("姓名:{0}", lzw.Name);
            Console.WriteLine("性别:{0}", lzw.Sex?"男":"女");
            Console.WriteLine("出生日期:{0}", lzw.Birth);
            Console.WriteLine("年龄:{0}", lzw.Age);
        }
    }
}

运行结果
运行结果

  • 属性没有储存数据的能力。
    从Age属性可以看出,可以获得年龄数据,但是不可设置年龄。并且Student类也没有age字段来储存年龄。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序鸡

如果帮到您,点个赞鼓励一下吧。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值