簡體   English   中英

在C#中,如何將默認get與顯式集合混合?

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

我想做這樣的事情:

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

我可以在那里設置價值嗎? 或者我是否必須明確定義get並向該類添加另一個字段?

沒有辦法。

  • 您可以自動實現setter和getter

     bool Property { get; set; } 
  • 或者手動實現

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

您可以使用默認屬性,使用編譯器生成的支持字段和getter和/或setter主體,或者使用自定義屬性。

一旦定義了自己的setter,就沒有編譯器生成的后備字段。 你必須自己制作一個,並定義吸氣體。

不是這種情況,自動屬性不是最合適的,因此您可以使用適當的實現屬性:

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

在許多情況下,您可以使用“自動屬性”功能,例如public int Age {get; 組; } = 43;

這是一個很好的參考http://www.informit.com/articles/article.aspx?p=2416187

Naji K.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM