c#程序可以以'{'开头吗?如果不是,为什么不呢?

can a c# program start with a '{'; if not, why not?

我不知道答案的问题在标题中说明,即:

c# 程序可以以 { 开头吗?如果不是,为什么不呢?

下面的所有内容都详细说明了我迄今为止的研究和思考过程:

注意:引用“c#语言规范5.0”;
使用vs2015社区版编译的代码。

从§2.2.2 Lexical grammar,这句话似乎暗示可以从{开始,因为{是一个记号:

"Every source file in a C# program must conform to the input production of the lexical grammar (§2.3)."

§2.4 令牌包括标点符号并且{是标点符号[§2.4.5运算符和标点符号]

但是,§9。名称spaces 开始"C# programs are organized using namespaces."

§9.1 编译单位:"A compilation-unit defines the overall structure of a source file."

compilation-unit:

extern-alias-directivesopt using-directivesopt global-attributesopt

namespace-member-declarations选择

程序的每个编译单元的

"namespace-member-declarations 贡献成员 到单个声明 space 全局名称space"

这样编译:

class Program
{
    static void Main(string[] args)
    {
    }
}

编译:

{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

因此,虽然 { 是一个标记,但它不提供成员...这可能就是编译器拒绝开头 {.

的原因

然而,namespace-member-declarations是可选的~~因此,也许编译器应该允许一个初始的{.

这是一个方块:

{
}

并非每个 方块 都必须是 something-block,请参阅下面的最后一个示例。

§1.5 声明

"A 允许在允许单个语句的上下文中编写多个语句。
块由写在定界符 {}."

之间的语句列表组成

另一个使用块进行范围编译的示例:

class Program
{
    static void Main(string[] args)
    {
        {
            System.Int16 integer = System.Int16.MaxValue;
        }
        {
            System.Int32 integer = System.Int32.MaxValue;
        }
    }
}

However, the namespace-member-declarations are optional ~~ for that reason, perhaps the compiler should allow an intial {.

不,这不是可选的意思 - 它意味着 "there doesn't have to be one",而不是 "you can have anything you like instead"。

基本上,一个编译单元由您提到的指令、全局属性和成员声明组成。这就是可以出现在顶层的所有内容。块不是成员声明(或全局属性或指令),因此不能出现在顶层。

还有一个提示:

A block permits multiple statements to be written in contexts where a single statement is allowed.

在顶层也不允许使用单个语句。这不是有效代码:

using System;

Console.WriteLine("Nope, can't have a statement here.");

同样,它不符合语法 - 它不是成员声明。

最后,即使 在顶层允许 块,也必须更改它们才能使您的代码有效 - 因为您正在尝试声明一个 class 在块中,这是无效的。