为什么原始数据类型在不包含 System 命名空间的情况下也能工作?

Why do primitive data types work without including the System namespace?

我读到所有原语都属于 System 命名空间。如果我注释掉 using System 我希望我的程序中出现构建错误,但它是 运行 成功。这是为什么?

因为intSystem.Int32的别名,而且"Int32"已经加上了它的命名空间前缀(即"fully qualified"),语法是合法的无需在代码顶部指定 using System;

下面的 MSDN 片段描述了这个概念-

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!");

Instead of:

System.Console.WriteLine("Hello, World!");

System.Int32(又名 "int")是后者。这是代码中的一个示例 -

//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; 需要取消注释才能消除错误。

其他参考文献-

如前所述,intSystem.Int32 类型的别名。原始类型的别名 被 C# 语言隐式识别。这是列表:

object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

因此,对于这些别名,也称为简单类型,您不需要指定任何命名空间。

当你使用int时,你基本上是在输入System.Int32。由于这是完全限定的类型名称,因此您实际上不需要 using System;

如果你这样做了,你的程序就会运行

 System.Int32 num = 0;

即使没有 using