12

例如,我们知道 C# 中的“int”类型只不过是一个结构,实际上是 System.Int32。如果是这样,那么如果“使用系统;” 在程序中被注释了,那么int类型应该是不能使用的。但仍然可以使用 int 类型。我的问题是,这些类型是从哪里来的?

//using System;
class Program
{
    static void Main() {
         int x = 0;  // it still work, though int is under System namespace, why??
    }
}
4

1 回答 1

24

int, string,等类型的别名object是内置在语言中的,不需要using指令就可以使用,不像DateTime例如。

但是,如果它有助于您思考它,您可以考虑int简称为global::System.Int32.

class Program
{
    static void Main() {
         int x = 0;
    }
}

转换为

class Program
{
    static void Main() {
         global::System.Int32 x = 0;
    }
}

事实上,因为类型别名是关键字,你甚至不能像你期望的那样重新定义它们:

public class int { } // Compiler error: Identifier expected; 'int' is a keyword

如果出于某种原因您想这样做,则必须像这样转义标识符:

public class @int { }

int x = 0;             // equivalent to global::System.Int32
@int y = new @int();   // equivalent to global::MyNamespace.@int
于 2013-09-15T17:58:06.357 回答