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,它包含了getset访问器。
  • get访问器用于获取age字段的值。
  • set访问器用于设置age字段的值,并包含了一些验证逻辑,确保年龄值在合理的范围内。
  • Main方法中,我们创建了三个Student类的新实例,并通过属性Age直接设置年龄为20。
  • 接着计算了这三个学生的平均年龄,并将结果输出到了控制台。
  • 异常处理逻辑用于捕获可能发生的异常。
相关推荐
AI_567828 分钟前
接口测试“零基础通关“:Postman从入门到自动化测试实战指南
开发语言·lua
是Yu欸36 分钟前
Rust 并发实战:从零构建一个内存安全的“番茄时钟”
开发语言·安全·rust
烛阴1 小时前
隐式vs显式:解密C#类型转换的底层逻辑
前端·c#
应用市场1 小时前
Qt QTreeView深度解析:从原理到实战应用
开发语言·数据库·qt
梦里不知身是客111 小时前
kafka作为Sink
c#·linq
猿来是你_L1 小时前
C# Dictionary 转换成 List
windows·c#·list
ooooooctober1 小时前
PHP代码审计框架性思维的建立
android·开发语言·php
864记忆2 小时前
Qt Widgets 模块中的函数详解
开发语言·qt
white-persist2 小时前
差异功能定位解析:C语言与C++(区别在哪里?)
java·c语言·开发语言·网络·c++·安全·信息可视化
q***72872 小时前
Golang 构建学习
开发语言·学习·golang