C# 中 get、set 属性的真正目的是什么?

发布于 2024-09-08 13:53:04 字数 360 浏览 1 评论 0原文

可能的重复:
属性与方法
C#:公共字段与自动属性

  • get,set 的真正目的是什么 C# 中的属性?
  • 任何好的前我应该什么时候使用 get,set 属性...

Possible Duplicates:
Properties vs Methods
C#: Public Fields versus Automatic Properties

  • What is the real purpose of get,set
    properties in c#?
  • Any good ex when should i use get,set properties...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

携余温的黄昏 2024-09-15 13:53:04

您需要它们来控制您的对象私有字段值。例如,如果您不想允许整数为空或负值。此外,封装对于在对象成员值更改时触发事件很有用。
示例

  bool started;
    public bool Started
    {
        get { return started; }
        set
        {
            started = value;
            if (started)
                OnStarted(EventArgs.Empty);
        }

    }

另一个示例

    int positiveNumber;

    public int PositiveNumber
    {
        get { return positiveNumber; }
        set {
            if (value < 0)
                positiveNumber = 0;
            else positiveNumber = value;
        }
    }

以及只读属性的另一个实现如下

    int positiveNumber;

    public int PositiveNumber
    {
        get { return positiveNumber; }

    }

you need them to have control over your object private fields values. for example if you don't wanna allow nulls or negative values for integers. Also, encapsulation is useful for triggering events on change of values of object members.
Example

  bool started;
    public bool Started
    {
        get { return started; }
        set
        {
            started = value;
            if (started)
                OnStarted(EventArgs.Empty);
        }

    }

another example

    int positiveNumber;

    public int PositiveNumber
    {
        get { return positiveNumber; }
        set {
            if (value < 0)
                positiveNumber = 0;
            else positiveNumber = value;
        }
    }

and also another implementation of read only properties could be as follows

    int positiveNumber;

    public int PositiveNumber
    {
        get { return positiveNumber; }

    }
任谁 2024-09-15 13:53:04

您指的是属性还是关键字 get;设置;

属性:简单地说,属性就是智能字段。聪明的是,当您想要获取或设置值时,您可以添加逻辑。用法示例:如果您想要验证为属性设置的值,或者如果您想要组合来自不同字段的值而不向公众公开这些字段。

关键字:这是创建带有支持字段(存储值的字段)的属性的 C# 简写。当您开始编写新代码并希望尽早完成界面时,它非常有用。

Did you mean just properties or the keywords get; set;?

Properties: to put it easily, properties are smart fields. Smart being you can add logic when you want to get or set the value. Usage example: if you want to validate the values being set to a property or if you want to combine values from different fields without exposing those fields to the public.

The keywords: this is a C# shorthand to create a property with a backing field (the field that stores the values). It's useful when you're starting a new code and wanted to do the interface as early as possible.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文