简体   繁体   中英

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. When I check the btnCountViewsAvg is null. I used static as I only want to have one Counts class in the application.

Can someone give me some advice on how I can assign a value to Counts.btnCountViewsAvg.BtnCount

It is your Counts.btnCountViewsAvg that is null. You need to instantiate that before being able to set the BtnCount property.

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:

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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