簡體   English   中英

如何為靜態類中的靜態對象的屬性賦值?

[英]How can I assign a value to a property of a static object inside a static class?

我有這個任務:

Counts.btnCountViewsAvg.BtnCount = 123;

以下是我使用的類:

public static class Counts
{
    public static BtnCountViews btnCountViewsAvg;
}

public class BtnCountViews // this class used in many places
{
    public int BtnCount { get; set; }
    public int Views { get; set; }
}

我想要做的是將123分配給BtnCount,但它說不能分配給null。 當我檢查btnCountViewsAvg為空時。 我使用靜態,因為我只想在應用程序中有一個Counts類。

有人可以給我一些關於如何為Counts.btnCountViewsAvg.BtnCount分配值的建議

你的Counts.btnCountViewsAvg是null。 您需要在能夠設置BtnCount屬性之前實例化它。

要實例化您需要執行以下操作的值:

Counts.btnCountViewsAvg = new BtwCountViews();

此外,您可以使用對象初始化器進行實例化,如下所示:

Counts.btnCountViewsAvg = new BtwCountViews { BtnCount = 123 };

為了確保只有在您執行以下操作后才能創建btnCountViewsAvg

public static class Counts
{
    public readonly static BtnCountViews btnCountViewsAvg = new BtnCountViews();
}

或者繼續使用Jon Skeets建議使用屬性而不是公共字段,這將是一個更好的方法:

public static class Counts
{
    public static ButtonCountViews ButtonCountViewsAvg { get; } = new ButtonCountViews();
}

注意我重命名了您的類以刪除縮寫。

您有兩種選擇:

  • 僅創建一個新對象

     public static class Counts { public static BtnCountViews btnCountViewsAvg = new BtnCountViews(); } 
  • 或者每次需要時創建它:

     Counts.btnCountViewsAvg = new BtnCountViews() { BtnCount = 123 }; 

您可能需要這樣的東西:使用BtnCount = 123創建BtnCountViews的實例並將其分配給靜態字段:

public static class Counts
{
    // we create a instance: new btnCountViewsAvg() 
    // then we set up a property of this instance: { BtnCount = 123, }
    public static BtnCountViews btnCountViewsAvg = new btnCountViewsAvg() {
      BtnCount = 123,
    };
}

暫無
暫無

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

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