请解释C#属性是如何工作的? [英] Please explain how C# properties work?

查看:122
本文介绍了请解释C#属性是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习C#有一段时间了,我已经在我的C#的书(深入浅出C#)遇到的属性。老实说,我不明白他们在用什么,我为什么要使用它们。我GOOGLE了他们几次,但仍然不能为我的生活了解它们。

I've been learning C# for a while now, and I've come across properties in my C# book (Head First C#). I honestly do not understand what they're used for, and why I should use them. I've googled them a few times but still cannot for the life of me understand them.

可有人请给我解释一下这个陌生的概念?

Can someone please explain to me this foreign concept?

谢谢,

Va​​rmitharen

Varmitharen

推荐答案

属性是用来充实面向对象编程的封装概念。

Properties are used to enrich the Encapsulation concept of Object-Oriented Programming.

即它们封装字段名成员,让你(开发人员)控制如何设置/获取这个变量就完成了。 ?例如:

i.e. They encapsulate a field-member and let you (the developer) control how setting/getting this variable is done. Example?

public class Person
{
    private int m_age;

    public int Age
    {
        set
        {
            if(value < 18)
                m_age = 18;
            else
                m_age = value;
        }
        get
        {
            return m_age;
        }
    }
}



看到了吗?使用属性年龄,我们保证的年龄最小设定值是18。

See? using property Age, we guaranteed that the minimum set value of age is 18.

这篇关于请解释C#属性是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆