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

Mat*_*att 11 .net c# setter properties automatic-properties

我想做这样的事情:

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

我可以在那里设置价值吗?或者我是否必须明确定义get并向该类添加另一个字段?

Ben*_*igt 12

您可以使用默认属性,使用编译器生成的支持字段和getter和/或setter主体,或者使用自定义属性.

一旦定义了自己的setter,就没有编译器生成的后备字段.你必须自己制作一个,并定义吸气体.


aba*_*hev 11

没有办法.


Jam*_*iec 5

不是这种情况,自动属性不是最合适的,因此您可以使用适当的实现属性:

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