【问题标题】:When does a static member of a class get accessed before the static constructor of the same class什么时候在同一个类的静态构造函数之前访问一个类的静态成员
【发布时间】: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


【解决方案1】:

为了处理上述情况,而不是使用构造函数来初始化静态主列表,我添加了对静态函数的显式调用,该函数将初始化静态主列表,然后可以检查主列表是否具有使用该值的值

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

【讨论】:

    猜你喜欢
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多