【发布时间】:2020-12-22 17:54:39
【问题描述】:
我有一个公共类和两个静态成员,我想使用静态构造函数设置这些静态成员的值。但是在静态构造函数初始化之前就已经从 .aspx 页面访问了该成员。
关于如何防止这种情况并让构造函数总是被击中的任何输入。
为此添加一个小代码参考:
public class test
{
public string var1 ;
public string Description;
public string var2;
public string var3;
public static List<Feature> MasterFeatureList = new List<Feature>();
static test()
{
try
{
if (MasterFeatureList.Count() == 0)
{
using (IM5Context context = new M5Context())
{
MasterFeatureList =
new
FeatureRepository(context).GetAll().Where(x => x.Enabled == true).ToList();
}
}
}
catch (System.Exception ex)
{
throw ex;
}
}
public static Dictionary<Feature.Values, test> Features = new Dictionary<Feature.Values, test>()
{
{
Feature.Values.xyz,
new test { var1 = MasterFeatureList.Find(x=>x.Id==(int) Feature.Values.xyz).Name, Description = "", var2 = "xyz", var3 = "xyz" }
},
// i have multiple other feature to be initilaized
上面的代码有一个静态构造函数,它有一个静态成员,我在静态字典中使用它来初始化值。但是字典在静态构造函数初始化之前就被访问了。
【问题讨论】:
-
您有什么证据表明这种情况正在发生?静态构造函数显式地在任何静态成员之前运行,所以如果这是一个 CLR 错误,我希望它已经显现(并已修复)。
-
您能否添加静态构造函数的代码、显然未初始化的成员以及调用它的 aspx 代码?
-
我已经添加了引用代码,在 aspx 中,var1 被引用为 test.Features[this.FeatureValue].var1 并抛出对象引用 null
标签: c# class static static-variables static-constructor