[英]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.