在使用C#应用程序时,我只是注意到在几个地方静态初始化程序彼此依赖,如下所示:
static private List<int> a = new List<int>() { 0 };
static private List<int> b = new List<int>() { a[0] };
Run Code Online (Sandbox Code Playgroud)
没有做任何有用的特殊工作.这只是运气吗?C#有解决这个问题的规则吗?
编辑:( re:Panos)在一个文件中,词汇顺序似乎是王道?跨文件怎么样?
看起来我尝试了这样的周期性依赖:
static private List<int> a = new List<int>() { b[0] };
static private List<int> b = new List<int>() { a[0] };
Run Code Online (Sandbox Code Playgroud)
并且该程序没有运行相同(测试套装全面失败,我没有看得更远).
考虑以下C#代码:
using System;
class Program
{
static string string1 = "AAA";
static string string2 = string1 + string3;
static string string3 = "BBB";
static void Main()
{
Console.WriteLine(string2);
}
}
Run Code Online (Sandbox Code Playgroud)
我今天早些时候写了一些这样的代码,并期望string2包含值AAABBB,但它只包含它AAA.我对静态变量的初始化顺序进行了一些阅读,但在编译过程中,我似乎更喜欢某种类型的警告或错误.
两个问题:
为什么允许这样的代码成功编译?(如果答案是:"因为那是C#规范的编写方式",那么为什么它是这样编写的?有没有理由我错过了为什么这不优选总是只抛出编译时错误?)
有没有办法获得编译时警告或其他类型的标志,如果我最后无意中再次编写这种代码?