【问题标题】:What are the differences between C# namespace declaration with semicolon and curly braces?使用分号和花括号的 C# 命名空间声明之间有什么区别?
【发布时间】:2023-01-14 07:55:13
【问题描述】:

我注意到 C# 中有两种不同的命名空间声明方法。

namespace FirstProgram;

namespace FirstProgram {...}

我正在寻找有关 C# 中两种命名空间声明的主要区别和用途的信息。

示例:带分号“;”

namespace FirstProgram; // Why use semecolon (;)?

class Program
{
    //fields and methods
}

示例:带大括号“{...}”

namespace FirstProgram // What is the difference in using curly braces ({...})?
{ 
    class Program
    {
        //fields and methods
    }
}

【问题讨论】:

  • 一样的。这只是一种不同的语法。带分号的部分较短较新。

标签: c#


【解决方案1】:

使用大括号意味着您将声明存在于该名称空间中的新类型。

//Declare a new class with a full name of Foo.Bar
namespace Foo
{
    class Bar
    {
    }
}

var x = new Foo.Bar();  //Bar exists in the Foo namespace

使用分号意味着下面的代码在使用对象时可以省略命名空间。

namespace Foo;
var x = new Bar(); //Instead of Foo.Bar you can just use Bar

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 2013-03-11
    • 2014-04-18
    • 1970-01-01
    相关资源
    最近更新 更多