简体   繁体   English

在C#中,如何将默认get与显式集合混合?

[英]In C#, how do you mix a default get with an explicit set?

I want to do something like this: 我想做这样的事情:

class Foo
{
    bool Property
    {
        get;
        set
        {
            notifySomethingOfTheChange();
            // What should I put here to set the value?
        }
    }
}

Is there anything I can put there to set the value? 我可以在那里设置价值吗? Or will I have to explicitly define the get and add another field to the class? 或者我是否必须明确定义get并向该类添加另一个字段?

There is no way. 没有办法。

  • You can either have both setter and getter auto-implemented 您可以自动实现setter和getter

     bool Property { get; set; } 
  • Or implement both manually 或者手动实现

     bool Property { get { return _prop; } set { _prop = value; } } 

You either have a default property, with compiler-generated backing field and getter and/or setter body, or a custom property. 您可以使用默认属性,使用编译器生成的支持字段和getter和/或setter主体,或者使用自定义属性。

Once you define your own setter, there is no compiler-generated backing field. 一旦定义了自己的setter,就没有编译器生成的后备字段。 You have to make one yourself, and define the getter body also. 你必须自己制作一个,并定义吸气体。

No this is the case where auto-properties are not the best fit, and therefore the point at which you go to proper implemented properties: 不是这种情况,自动属性不是最合适的,因此您可以使用适当的实现属性:

class Foo
{
    private bool property;
    public bool Property
    {
        get
        {
            return this.property;
        }
        set
        {
            notifySomethingOfTheChange();
            this.property = value
        }
    }
}

In many cases you can use the "Auto Property" feature eg public int Age { get; 在许多情况下,您可以使用“自动属性”功能,例如public int Age {get; set; 组; } = 43; } = 43;

This is a good reference http://www.informit.com/articles/article.aspx?p=2416187 这是一个很好的参考http://www.informit.com/articles/article.aspx?p=2416187

Naji K. Naji K.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM