2012-07-21 114 views
1

什么是C#中的int?它是一个关键字,还是来自system.ValueTypes派生的类?如果它是一个关键字,然后怎么做下面几行编译什么是C#中的int?

int i = new int(); // If int is not a class then how does it have a default constructor 

Console.WriteLine(i.ToString()); // If int is not a class then how does it have member functions 

如果int是一个类,那么它为什么没有必要总是new初始化呢?以下行如何编译?

int i = 8; 
+3

谁说“结构”或“价值型” *不能*有方法?这是一些Java废话说:)'int'是'System.Int32'这是'struct'类型。 (为了使生活更简单,编译器知道各种“文字”结构,如整数,浮点值和字符串,但它是一个固定的集合,例如GUID没有“literal”,所以'new Guid(string)是必需的。) – 2012-07-21 04:08:46

+1

所有值类型都可以有方法,Java是愚蠢的例外。 – Ryan 2012-07-21 04:11:35

+0

'int i = 8'编译的原因与'string foo =“bar”'编译的原因相同。 '8'是'int'类型的字面值,就像''bar“'是'string'类型的字面值。 – cdhowie 2012-07-21 04:12:08

回答

3

int是对于值类型(structSystem.Int32别名关键字。作为一个常规值类型,我相信它的继承是System.Object - >System.ValueType - >System.Int32

由于int具有文字符号,如字符串和其他数字类型,您可以创建它的实例,而不需要new

+0

如果int是_struct_'System.Int32'的别名,那么它是如何继承来自'System.Object'类? – user1232138 2012-07-21 04:16:44

+0

@ user1232138:*所有*值类型都有'System.Object'作为间接基类。 – Gabe 2012-07-21 04:21:04

0

要使用代码解释代码:

Console.WriteLine(typeof(int) == typeof(Int32)); // Outputs: True 
Console.WriteLine(typeof(int).Name); // Outputs: Int32 
相关问题