问题描述
我有一个公共类,并且有两个静态成员,我想使用一个静态构造函数设置这些静态成员的值。但是,即使在静态构造函数对其进行初始化之前,也要从.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
上面的代码有一个带有静态成员的静态构造函数,我在静态字典中使用它来初始化值。
解决方法
为了处理上述情况,而不是使用构造函数初始化静态主列表,我向静态函数添加了显式调用,该调用将初始化静态主列表,然后可以检查主列表是否具有使用该值的值
public static string SetName(int featureId)
{
using (IM5Context context = new M5Context())
{
if (MasterFeatureList.Count() == 0)
{
MasterFeatureList = new xyzRepository(context).GetAll().Where(x => x.Enabled == true).ToList();
}
if (MasterFeatureList.Any(x => x.Id == featureId))
{
return MasterFeatureList.Find(x => x.Id == featureId).Name;
}
else
{
return new FeatureRepository(context).GetById(featureId).Name;
}
}
}
public static readonly Dictionary<Feature.Values,test> Features = new Dictionary<Feature.Values,test>()
{
{
Feature.Values.xyz,new test { ServiceName = SetName((int)Feature.Values.xyz),Description = "",KbUrl = "xyz",TemplateAppendix = "xyz" }
},