是“文本顺序"吗?跨正式定义的部分类? [英] Is the "textual order" across partial classes formally defined?

查看:12
本文介绍了是“文本顺序"吗?跨正式定义的部分类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特别是关于字段初始值设定项(在本例中为静态) - ECMA 334 中的第 17.11 节:

Specifically, in relation to field initializers (in this case, static) - §17.11 in ECMA 334:

如果一个类包含任何带有初始化器的静态字段,这些初始化器将在执行静态构造函数之前立即按文本顺序执行.

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 中记录的顺序有关".这是正确的吗?

Now, if we have multiple partial classes in separate files, is that order determined anywhere? My gut says "not formally defined, but probably relates to the order included in the csproj, or the order noted to csc". Is this correct?

(是的,我意识到完全避免歧义会更好 - 可能通过将所有初始化移动到静态构造函数).

(and yes, I realise it would be better to avoid the ambiguity completely - probably by moving all the initialization to a static constructor).

例如,如果我有 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;但是,如果这是:

then this is Foo then Bar; if, however, this is:

<Compile Include="b.cs" />
<Compile Include="a.cs" />

然后是 Bar 然后是 Foo.这支持观察,但没有强烈声明.§8.7.13(部分类型声明)对组合 partial 类时的顺序没有任何评论.所以;从 C# 语言规范或工具文档中,我们可以说些什么?

then it is Bar then Foo. This supports the observation, but does not state it strongly. §8.7.13 (Partial type declarations) makes no comment on the order when combining partial classes. So; is there anything stronger we can say here, either from the C# language spec or from the tooling documentation?

此外,它的行为与 csc a.cs b.cscsc b.cs a.cs 相似.

Additionally, it behaves similarly with csc a.cs b.cs vs csc b.cs a.cs.

推荐答案

这是 C# 规范中的另一个片段,与您的片段一起使用,似乎表明这是未定义的行为:

Here's another snippet from the C# spec which, taken with your snippet, appears to settle that this is undefined behaviour:

10.2.6 成员

[...] 类型中成员的排序对于C# 代码,但在与其他语言交互时可能很重要和环境.在这些情况下,成员在一个在多个部分中声明的类型未定义.

[...] 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.

公平地说,它确实表示很少重要,而不是无关紧要:)

To be fair, it does say rarely significant, not insignificant :).

这篇关于是“文本顺序"吗?跨正式定义的部分类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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