我在阅读《关于软件的更多Joel》时,偶然看到Joel Spolsky说,有一种特殊类型的程序员知道Java/ c#(面向对象编程语言)中int和Integer的区别。

那么,有什么不同呢?


当前回答

在Java中,'int'类型是一个原语,而'Integer'类型是一个对象。

在c#中,'int'类型与System相同。Int32,是一个值类型(即更像java 'int')。整数(就像任何其他值类型一样)可以被装箱(“包装”)到一个对象中。


对象和原语之间的区别在某种程度上超出了这个问题的范围,但总结一下:

对象为多态性提供了便利,通过引用传递(或者更准确地说,通过值传递引用),并从堆中分配。相反,原语是按值传递的不可变类型,通常从堆栈中分配。

其他回答

“int”是原始数据类型,是Java包装类中的“Integer”。“Integer”可以用作需要对象的方法的参数,而“int”可以用作需要整数值的方法的参数,可用于算术表达式。

int is a primitive datatype whereas Integer is an object. Creating an object with Integer will give you access to all the methods that are available in the Integer class. But, if you create a primitive data type with int, you will not be able to use those inbuild methods and you have to define them by yourself. But, if you don't want any other methods and want to make the program more memory efficient, you can go with primitive datatype because creating an object will increase the memory consumption.

int在库函数c#中是预定义的,但在java中我们可以创建Integer对象

Java已经回答了这个问题,下面是c#的答案:

“Integer”在c#中不是一个有效的类型名称,“int”只是System.Int32的别名。此外,与Java(或c++)不同,c#中没有任何特殊的基本类型,c#中类型的每个实例(包括int)都是一个对象。下面是一些演示代码:

void DoStuff()
{
    System.Console.WriteLine( SomeMethod((int)5) );
    System.Console.WriteLine( GetTypeName<int>() );
}

string SomeMethod(object someParameter)
{
    return string.Format("Some text {0}", someParameter.ToString());
}

string GetTypeName<T>()
{
    return (typeof (T)).FullName;
}

在Java中,int类型是基本数据类型,而Integer类型是对象。

在c#中,int类型也是一种数据类型,与System.Int32相同。整数(就像任何其他值类型一样)可以被装箱(“包装”)到一个对象中。