为什么原始数据类型可以在不包含 System 命名空间的情况下工作? [英] Why do primitive data types work without including the System namespace?
问题描述
我读到所有原语都属于 System
命名空间.如果我注释掉 using System
,我希望我的程序中存在构建错误.但是,它运行成功.这是为什么?
I read that all primitives fall under the System
namespace. If I comment out using System
, I would expect there to be a build error in my program. However, it is running successfully. Why is this?
推荐答案
这是因为 int
是 System.Int32
的别名,而Int32"已经是以其命名空间为前缀(即完全限定"),语法是合法的,无需在代码顶部指定 using System;
.
It's because int
is an alias for System.Int32
, and since the "Int32" is already prefixed with its namespace (ie. "fully qualified"), the syntax is legal without having to specify using System;
at the top of your code.
下面的 MSDN 片段描述了这个概念-
The MSDN snippet below describes this concept-
大多数 C# 应用程序都以一段 using 指令开头.本节列出了应用程序将使用的命名空间经常,并使程序员免于指定完全限定的每次使用其中包含的方法时命名.为了例如,通过包含以下行:
Most C# applications begin with a section of using directives. This section lists the namespaces that the application will be using frequently, and saves the programmer from specifying a fully qualified name every time that a method that is contained within is used. For example, by including the line:
using System;
在程序开始时,程序员可以使用以下代码:
At the start of a program, the programmer can use the code:
Console.WriteLine("Hello, World!");
代替:
System.Console.WriteLine("Hello, World!");
System.Int32
(又名int")将是后者.这是代码中的一个示例 -
System.Int32
(aka "int") would be the latter. Here is an example of this in code -
//using System;
namespace Ns
{
public class Program
{
static void Main(string[] args)
{
System.Int32 i = 2; //OK, since we explicitly specify the System namespace
int j = 2; //alias for System.Int32, so this is OK too
Int32 k = 2; //Error, because we commented out "using System"
}
}
}
由于第 11 行不是完全限定/别名完全限定类型,using System;
需要取消注释才能消除错误.
Since line 11 is not fully qualified / aliasing a fully qualified type, using System;
would need to be uncommented for the error to go away.
其他参考资料-
内置类型表(C# 参考)(列出所有内置类型及其 .NET 框架等效项)
Built-In Types Table (C# Reference) (Lists all the built-in types, and their .NET framework equivalents)
这篇关于为什么原始数据类型可以在不包含 System 命名空间的情况下工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!