为什么要在C#中确实为了此事的静态初始化? [英] Why in C# does order matter for static initialization?

查看:111
本文介绍了为什么要在C#中确实为了此事的静态初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这代码中有不工作的C#的定义良好的行为:

This code has the well defined behavior in C# of not working:

class Foo
{
    static List<int> to = new List<int>( from ); // from is still null
    static IEnumerable<int> from = Something();
}

注:我不是问如何解决代码我已经知道该怎么做

,这是什么理由? C#已经不运行时检查,以检测静态成员第一次访问。为什么不呢?这延伸到每个成员的事情,让他们在需要运行,甚至更好的让编译器弄清楚的顺序在编译时

What is the justification for this? C# already does run time checks to detect the first access to static members. Why not extend this to a per member thing and have them run on demand or even better have the compiler figure out the order at compile time?

BTW:我想的一样问题(或几乎相同),也适用于非静态成员。

BTW: I think the same question (or almost the same) also holds for non static members.

推荐答案

我可以根据初始化顺序设想一个程序员,由于副作用与其他静态类。你和我都知道,这取决于副作用是不好的做法,但它并不一定违法。

I can envision a programmer depending on initialization order due to side effects with other static classes. You and I both know that depending on side effects is bad practice, but it's not necessarily illegal.

考虑是这样的:

class Foo
{
    static string header = Bar.GetHeader();
    static string version = Bar.GetVersion();
}

Bar.GetVersion 假定 Bar.GetHeader 被调用。如果编译器可以自由更改初始化顺序,那么程序员将不能保证初始化顺序。

And Bar.GetVersion assumes that Bar.GetHeader has been called. If the compiler were free to change the initialization order, then the programmer wouldn't be able to guarantee the initialization order.

丑,理所当然,但完全合法的。如果你想像二阶效应(即所谓的本身取决于有副作用类的静态方法),你看,这是不可能的编译器能可靠地重新安排什么,只是因为它是不可能的(一般)编译器重新安排函数调用顺序在静态构造函数。

Ugly, granted, but perfectly legal. If you imagine second-order effects (i.e. called static methods that themselves depend on classes that have side effects), you see that it's impossible for the compiler to reliably rearrange anything, just as it's impossible (in general) for the compiler to rearrange the order of function calls in your static constructor.

这篇关于为什么要在C#中确实为了此事的静态初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆