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

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

问题描述

具体而言,在相对于字段初始化(在这种情况下,静态) - §17.11在ECMA 334:

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.

现在,如果我们有多个部分类在单独的文件,这是为了在任何地方确定的?我的直觉说没有正式定义,但可能涉及到包括在的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" />

那么这是然后酒吧;如果,然而,这是:

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

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

那么它就是酒吧然后。此载体的观察,但不强烈说明它。 §8.7.13(部分类型声明)结合部分类时,使顺序没有评论。所以;有什么都强,我们可以说,在这里,无论是从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.cs 的行为类似于VS CSC 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#code,与其他语言的接口时,但可能会显著
  和环境。在这些情况下,的件内的排序
  在多个部分中声明的类型是不确定的。

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

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

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