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

问题描述 投票:19回答:3

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

Attached the snap of my sample program.

c# .net namespaces primitive
3个回答
23
投票

这是因为intSystem.Int32的别名,并且因为“Int32”已经以其命名空间为前缀(即“完全限定”),所以语法是合法的,而无需在代码顶部指定using System;

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

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

using System;

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

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

代替:

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;才能使错误消失。

其他参考 -


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

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


4
投票

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

如果你这样做,你的计划将会奏效

 System.Int32 num = 0;

即使没有using

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.