具体来说,关于字段初始值设定项(在本例中为静态)- ECMA 334 中的 §17.11:
If a class contains any static fields with initializers, those initializers are executed in textual order immediately prior to executing the static constructor.
现在,如果我们在单独的文件中有多个 partial
类,那么这个顺序是在任何地方确定的吗?我的直觉说“没有正式定义,但可能与 csproj 中包含的顺序或记录到 csc 的顺序有关”。这是正确的吗?
(是的,我意识到完全避免歧义会更好 - 可能通过将所有初始化移动到静态构造函数)。
例如,如果我有a.cs
:
using System;
partial class Program
{
private static int Foo = Write("Foo");
static int Write(string name)
{
Console.WriteLine(name);
return 0;
}
static void Main()
{
Console.WriteLine("[press any key]");
Console.ReadLine();
}
}
和b.cs
:
partial class Program
{
private static int Bar = Write("Bar");
}
和:
<Compile Include="a.cs" />
<Compile Include="b.cs" />
然后这是 Foo
然后是 Bar
;但是,如果这是:
<Compile Include="b.cs" />
<Compile Include="a.cs" />
然后是 Bar
然后是 Foo
。这支持观察,但没有强烈声明。 §8.7.13(部分类型声明)在组合 partial
类时没有对顺序进行评论。所以; C# 语言规范或工具文档中有什么我们可以在这里说的更有力的吗?
此外,csc a.cs b.cs
与 csc b.cs a.cs
的行为相似。
最佳答案
这是来自 C# 规范的另一个片段,与您的片段一起使用,似乎确定这是未定义的行为:
10.2.6 Members
[...] The ordering of members within a type is rarely significant to C# code, but may be significant when interfacing with other languages and environments. In these cases, the ordering of members within a type declared in multiple parts is undefined.
公平地说,它确实说很少重要,而不是无关紧要:)。
关于c# - 跨部分类的 "textual order"是否正式定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7965830/