微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

预期产量&输出我进入调试模式,并在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(){}或者可能通过访问另一个(可能是虚拟的)静态变量

原文地址:https://www.jb51.cc/csharp/98512.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐