加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 未在Release – Compiler / clr bug中初始化静态成员变量

发布时间:2020-12-15 18:25:54 所属栏目:百科 来源:网络整理
导读:预期产量输出我进入调试模式,并在VS2010,.NET 4.0下发布模式: bar constructmain 在VS2010调试器和WinDbg下的发布模式下输出: main 程序在VS2005,.NET 2.0上不会出现此行为 using System;namespace static_init{ public class bar { public bar() { Consol
预期产量&输出我进入调试模式,并在VS2010,.NET 4.0下发布模式:
bar construct
main

在VS2010调试器和WinDbg下的发布模式下输出:

main

程序在VS2005,.NET 2.0上不会出现此行为

using System;

namespace static_init
{
    public class bar
    {
        public bar()
        {
            Console.WriteLine("bar construct");
        }
    }

    class Program
    {
        public static bar blah = new bar();

        static void Main(string[] args)
        {
            Console.WriteLine("main");
            Console.ReadLine();
        }
    }
}

可能相关:
Static constructor can run after the non-static constructor. Is this a compiler bug?

更新

在我的实际代码构造函数bar()中使用C(非托管)初始化一些互操作代码.它需要在此库中的任何其他内容之前发生 – 是否有任何方法可以确保在没有放入init()函数的情况下触及库中的所有静态(具有未外部引用的副作用)?

未来搜索者的注意事项:我正在使用SWIG,这是他们在包装器生成代码中做出的假设. SWIGStringHelper是目前的罪犯,可能会有更多.

结论

更新到SWIG的2.0版本,它根据新版.NET的需要放入静态构造函数.

解决方法

它可能会被优化,因为你不使用它.

它也不是编译器错误,它在语言规范中.

17.4.5.1 Static field initialization

The static field variable initializers
of a class declaration correspond to a
sequence of assignments that are
executed in the textual order in which
they appear in the class declaration.
If a static constructor (§17.11)
exists in the class,execution of the
static field initializers occurs
immediately prior to executing that
static constructor. Otherwise,the
static field initializers are executed
at an implementation-dependent time
prior to the first use of a static
field of that class

由于您从不使用Program类的静态字段,因此无法保证静态初始化程序运行(尽管它可能……上面的’实现相关时间’)

更新
您可以通过使程序具有静态构造函数来完成您想要的任务.

static Program(){}或者可能通过访问另一个(可能是虚拟的)静态变量

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读