C# 什么是属性

1.属性Aproperty)是一种用于访问对象或类型的特征的成员,特征反映了状态

2.属性是字段的自然扩展

  • 从命名上看,field更偏向于实例对象在内存中的布局,property更偏向于反映现实世界对象的特征
  • 对外:暴露数据,数据可以是存储在字段里的,也可以是动态计算出来的
  • 对内:保护字段不被非法值"污染"

3.属性由Get/Set方法对进化而来

最初的用来保护字段的Get/Set方法,如以下代码:(C++与Java语言仍然在使用Get/Set方法)

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PropertyExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Student stu1 = new Student();
                stu1.SetAge(20);//设置值
                Student stu2 = new Student();
                stu2.SetAge(20);
                Student stu3 = new Student();
                stu3.SetAge(20);
                int avgAge = (stu1.GetAge() + stu2.GetAge() + stu3.GetAge()) / 3;//获取值
                Console.WriteLine(avgAge);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
    }

    class Student
    {
        private int age;//私有字段,从外界不能直接访问该字段

        //用一对方法将该字段保护起来,一个方法获取值(Get),另一个为字段设置值(Set)
        public int GetAge()
        {
            return this.age;
        }
        public void SetAge(int value)
        {
            if(value>=0&&value<=120)
                {
                this.age = value;
                }
            else 
            {
                throw new Exception("Age value has error.");
            }
        }
    }
}

分析代码:

  1. age字段:这是一个私有字段,用于存储年龄的值。
  2. GetAge方法 :这是一个公有方法,用于获取age字段的值。
  3. SetAge方法 :这是一个公有方法,用于设置age字段的值。它还包含了一些验证逻辑,确保年龄值在合理的范围内。

而属性提供了一种更简洁的方式来访问和修改字段的值,并允许您在访问或修改字段时执行额外的操作,如验证等。

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PropertyExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Student stu1 = new Student();
                stu1.Age = 20;
                Student stu2 = new Student();
                stu2.Age = 20;
                Student stu3 = new Student();
                stu3.Age = 20;
                int avgAge = (stu1.Age + stu2.Age + stu3.Age) / 3;
                Console.WriteLine(avgAge);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
    }

    class Student
    {
        private int age;//私有字段,从外界不能直接访问该字段

        public int Age  //属性,首字母大写
        {
            get
            {
                return this.age;
            }
            set
            {
                //不用声明value,在特定的方法中为上下文关键字,代表传进来的值
                if (value >= 0 && value <= 120)
                {
                    this.age = value;
                }
                else
                {
                    throw new Exception("Age value has error.");
                }
            }

            
        }
    }
}

代码分析:

  • 定义了一个Student类,它包含一个私有字段age。
  • 还定义了一个属性Age,它包含了get和set访问器。
  • get访问器用于获取age字段的值。
  • set访问器用于设置age字段的值,并包含了一些验证逻辑,确保年龄值在合理的范围内。
  • 在Main方法中,我们创建了三个Student类的新实例,并通过属性Age直接设置年龄为20。
  • 接着计算了这三个学生的平均年龄,并将结果输出到了控制台。
  • 异常处理逻辑用于捕获可能发生的异常。
相关推荐
饮水桶_T15 小时前
JAVA IO流笔记
开发语言·数据结构·算法
Felven17 小时前
C. Brr Brrr Patapim
c语言·开发语言
路溪非溪19 小时前
python标准库使用总结
开发语言·python
SomeOtherTime20 小时前
Rust 面向对象介绍(AI回答)
开发语言·python·rust
zh_xuan20 小时前
kotlin常见面试题
开发语言·kotlin·面试题
草莓熊Lotso1 天前
【C++ 基于微服务的即时通讯系统】文件存储子服务实战:UUID生成、文件IO封装与全接口单元测试
开发语言·网络·数据库·c++·微服务·架构·单元测试
huaqianzkh1 天前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#
沐晓时光1 天前
C语言入门,内存函数知识讲解
c语言·开发语言
David猪大卫2 天前
【C++修炼】map 和 set 的使用
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
用户3721574261352 天前
C# 实现 Excel 单元格保护:锁定公式并允许编辑指定区域
c#·ai编程·编程语言