【问题标题】:private set property the proper way to set within the class? c# [duplicate]私有设置属性在类中设置的正确方法? c# [重复]
【发布时间】:2013-01-19 03:48:07
【问题描述】:

可能重复:
What is the best way to access properties from the same class, via accessors or directly?

我还在学习 C#。无论如何,我有一个简单的问题,但我不确定这样做的正常方法。假设我在课堂上有以下内容

private int _questionNo;

public int QuestionNo

    {
        get
        {
            return _questionNo;
        }

        private set
        {
            _questionNo = value;
            PropChanged("QuestionNo");
        }

    }

如果我想在类本身中设置属性,我应该使用

_questionNo = number;

QuestionNo = number;

【问题讨论】:

    标签: c# oop class properties


    【解决方案1】:

    您应该始终使用公共 getter-setter,并且永远不要触摸远离 Getter-Setter 内部的私有支持字段,除非您当然不希望 Setter 内部的事件发生。

    QuestionNo = number;
    

    这样做的原因是,如果您需要在 Setter 中更改您希望发生的某些事情,您不必更改所有变量。

    【讨论】:

      【解决方案2】:

      您可能应该使用QuestionNo 属性,除非出于某种原因您不希望PropChanged 触发

      【讨论】:

        【解决方案3】:

        使用QuestionNo = number 属性。 我宁愿建议使用可以访问和指定属性的公共方法,例如。,

        public changemethod(int value)
        {
            this.QuestionNo = value;
        }
        public int QuestionNo { get; set; }
        

        【讨论】:

        • 既然可以直接访问setter,为什么还要使用方法呢?
        猜你喜欢
        • 2018-09-29
        • 2012-10-29
        • 2012-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-30
        相关资源
        最近更新 更多