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

时间:2015-08-08 14:20:38

标签: c# .net namespaces primitive

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

Attached the snap of my sample program.

3 个答案:

答案 0 :(得分:23)

这是因为intSystem.Int32的别名,并且由于“Int32”已经以其命名空间为前缀(即“完全限定”),因此语法是合法的,无需指定{代码顶部的{1}}。

下面的MSDN摘要描述了这个概念 -

  

大多数C#应用程序都以using指令的一部分开头。本节列出了应用程序将使用的命名空间   经常,并保护程序员不指定完全限定   每次使用包含在其中的方法时命名。对于   例如,包括以下行:

using System;
     

在程序开始时,程序员可以使用代码:

using System;
     

而不是:

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

System.Console.WriteLine("Hello, World!"); (又名“int”)将是后者。以下是代码中的示例 -

System.Int32

由于第11行不是完全限定类型的完全限定/别名,因此需要取消注释//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" } } } 才能使错误消失。

其他参考资料 -

答案 1 :(得分:8)

正如前面提到的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

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

答案 2 :(得分:4)

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

如果你做了

你的程序会有效
 System.Int32 num = 0;

即使没有using