简体   繁体   English

如何为静态类中的静态对象的属性赋值?

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

I have this assignment: 我有这个任务:

Counts.btnCountViewsAvg.BtnCount = 123;

Here are the classes that I use: 以下是我使用的类:

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; }
}

What I would like to do is to assign 123 to BtnCount but it says cannot assign to a null. 我想要做的是将123分配给BtnCount,但它说不能分配给null。 When I check the btnCountViewsAvg is null. 当我检查btnCountViewsAvg为空时。 I used static as I only want to have one Counts class in the application. 我使用静态,因为我只想在应用程序中有一个Counts类。

Can someone give me some advice on how I can assign a value to Counts.btnCountViewsAvg.BtnCount 有人可以给我一些关于如何为Counts.btnCountViewsAvg.BtnCount分配值的建议

It is your Counts.btnCountViewsAvg that is null. 你的Counts.btnCountViewsAvg是null。 You need to instantiate that before being able to set the BtnCount property. 您需要在能够设置BtnCount属性之前实例化它。

To instantiate the value you need to do the following: 要实例化您需要执行以下操作的值:

Counts.btnCountViewsAvg = new BtwCountViews();

Furthermore you could instantiate using the object initialiser it like so: 此外,您可以使用对象初始化器进行实例化,如下所示:

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

In order to ensure that btnCountViewsAvg is only created once you could do the following: 为了确保只有在您执行以下操作后才能创建btnCountViewsAvg

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

Or to follow on from Jon Skeets suggestion with using a property rather than a public field this would be a better approach: 或者继续使用Jon Skeets建议使用属性而不是公共字段,这将是一个更好的方法:

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

Note I renamed your class to remove the abbreviation. 注意我重命名了您的类以删除缩写。

You have two options: 您有两种选择:

  • Create new object only once 仅创建一个新对象

     public static class Counts { public static BtnCountViews btnCountViewsAvg = new BtnCountViews(); } 
  • Or create it every time you need it: 或者每次需要时创建它:

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

You, probably, want something like this: create an instance of BtnCountViews with BtnCount = 123 and assign it to static field: 您可能需要这样的东西:使用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