我做了一些搜索,我认为以下代码保证产生输出:
B.X = 7
B.X = 0
A.X = 1
A = 1, B = 0
Run Code Online (Sandbox Code Playgroud)
static class B
{
public static int X = 7;
static B() {
Console.WriteLine("B.X = " + X);
X = A.X;
Console.WriteLine("B.X = " + X);
}
}
static class A
{
public static int X = B.X + 1;
static A() {
Console.WriteLine("A.X = " + X);
}
}
static class Program
{
static void Main() {
Console.WriteLine("A = {0}, B = {1}", …Run Code Online (Sandbox Code Playgroud) 此代码在C#中具有明确定义的行为:
class Foo
{
static List<int> to = new List<int>( from ); // from is still null
static IEnumerable<int> from = Something();
}
Run Code Online (Sandbox Code Playgroud)
注意:我不是问如何修复该代码,因为我已经知道如何做到这一点
这有什么理由?C#已经进行了运行时检查,以检测对静态成员的第一次访问.为什么不将它扩展到每个成员的东西并让它们按需运行,甚至更好的让编译器在编译时弄清楚顺序?
顺便说一句:我认为同样的问题(或几乎相同)也适用于非静态成员.