Java 和 C# 中 int 和 Integer 有什么区别?

发布于 2024-07-03 23:54:32 字数 324 浏览 6 评论 0原文

我来的时候正在阅读更多 Joel 的软件 Joel Spolsky 讲述了特定类型的程序员知道 int< 之间的区别/code> 和 Java/C#(面向对象编程语言)中的 Integer

那么区别是什么呢?

I was reading More Joel on Software when I came across Joel Spolsky saying something about a particular type of programmer knowing the difference between an int and an Integer in Java/C# (Object-Oriented Programming Languages).

So, what is the difference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(26

三岁铭 2024-07-10 23:54:42

int 是原始数据类型,而 Integer 是对象。
使用 Integer 创建对象将使您可以访问 Integer 类中可用的所有方法。
但是,如果您使用 int 创建原始数据类型,您将无法使用这些 inbuild 方法,而必须自己定义它们。
但是,如果您不需要任何其他方法并且希望提高程序的内存效率,则可以使用原始数据类型,因为创建对象会增加内存消耗。

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.

素年丶 2024-07-10 23:54:42

(Java版本)
简单来说,int 是原语(不能有空值),Integer 是 int 的包装对象。

一个使用 Integer 与 int 的例子,当你想与 int 变量再次进行比较时,它会抛出错误。

int a;
//assuming a value you are getting from data base which is null
if(a ==null) // this is wrong - cannot compare primitive to null
{
do something...}

Instead you will use,
Integer a;
//assuming a value you are getting from data base which is null
if(a ==null) // this is correct/legal
{ do something...}

(Java Version)
In Simple words int is primitive (cannot have null value) and Integer is wrapper object for int.

One example where to use Integer vs int, When you want to compare and int variable again null it will throw error.

int a;
//assuming a value you are getting from data base which is null
if(a ==null) // this is wrong - cannot compare primitive to null
{
do something...}

Instead you will use,
Integer a;
//assuming a value you are getting from data base which is null
if(a ==null) // this is correct/legal
{ do something...}
抱着落日 2024-07-10 23:54:41

int 是一种原始数据类型。
Integer 是一个包装类。 它可以将 int 数据存储为对象。

int is a primitive data type.
Integer is a wrapper class. It can store int data as objects.

贪了杯 2024-07-10 23:54:41

在java中,根据我的知识,如果你是学习者,那么当你写 int a; 时 然后在 java generic 中它将编译类似 Integer a = new Integer() 的代码。
因此,根据泛型,不使用 Integer,而是使用 int。
所以那里有如此大的差异。

In java as per my knowledge if you learner then, when you write int a; then in java generic it will compile code like Integer a = new Integer().
So,as per generics Integer is not used but int is used.
so there is so such difference there.

夜吻♂芭芘 2024-07-10 23:54:40

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

int is predefined in library function c# but in java we can create object of Integer

〃安静 2024-07-10 23:54:40

01。 整数可以为空。 但int不能为null。

Integer value1 = null; //OK

int value2 = null      //Error

02. 只能将包装类类型值传递给任何集合类。

(包装类 - Boolean、Character、Byte、Short、Integer、Long、Float、Double)

List<Integer> element = new ArrayList<>();
int valueInt = 10;
Integer  valueInteger = new Integer(value);
element.add(valueInteger);

但是通常我们将原始值添加到集合类中? 第02点正确吗?

List<Integer> element = new ArrayList<>();
element.add(5);

是的,02 是正确的,因为自动装箱。

自动装箱是java编译器进行的自动转换
原始类型与其相应的包装类之间。

然后 5 通过自动装箱转换为整数值。

01. Integer can be null. But int cannot be null.

Integer value1 = null; //OK

int value2 = null      //Error

02. Only can pass Wrapper Classes type values to any collection class.

(Wrapper Classes - Boolean,Character,Byte,Short,Integer,Long,Float,Double)

List<Integer> element = new ArrayList<>();
int valueInt = 10;
Integer  valueInteger = new Integer(value);
element.add(valueInteger);

But normally we add primitive values to collection class? Is point 02 correct?

List<Integer> element = new ArrayList<>();
element.add(5);

Yes 02 is correct, beacouse autoboxing.

Autoboxing is the automatic conversion that the java compiler makes
between the primitive type and their corresponding wrapper class.

Then 5 convert as Integer value by autoboxing.

╭ゆ眷念 2024-07-10 23:54:39

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

"int" is primitive data-type and "Integer" in Wrapper Class in Java. "Integer" can be used as an argument to a method which requires an object, where as "int" can be used as an argument to a method which requires an integer value, that can be used for arithmetic expression.

陪你搞怪i 2024-07-10 23:54:39

在Java中,int是一种原始数据类型,而Integer是一个Helper类,它用于将一种数据类型转换为另一种数据类型。

例如:

double doubleValue = 156.5d;
Double doubleObject  = new Double(doubleValue);
Byte myByteValue = doubleObject.byteValue ();
String myStringValue = doubleObject.toString();

原始数据类型存储在最快的可用内存中,而 Helper 类很复杂,并且存储在堆内存中。

参考“David Gassner”Java Essential Training。

In Java int is a primitive data type while Integer is a Helper class, it is use to convert for one data type to other.

For example:

double doubleValue = 156.5d;
Double doubleObject  = new Double(doubleValue);
Byte myByteValue = doubleObject.byteValue ();
String myStringValue = doubleObject.toString();

Primitive data types are store the fastest available memory where the Helper class is complex and store in heep memory.

reference from "David Gassner" Java Essential Training.

何必那么矫情 2024-07-10 23:54:38

在 Java 中,int 类型是原始数据类型,而 Integer 类型是对象。

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

In Java, the int type is a primitive data type, where as the Integer type is an object.

In C#, the int type is also a data type same as System.Int32. An integer (just like any other value types) can be boxed ("wrapped") into an object.

烟酉 2024-07-10 23:54:38

Java 和 C# 中的 int 和 Integer 是两个不同的术语,用于表示不同的事物。 它是可以分配给可以精确存储的变量的原始数据类型之一。 一次其声明类型的一个值。

例如:

int number = 7;

其中 int 是分配给变量 number 的数据类型,该变量保存值 7。 所以 int 只是一个基元而不是一个对象。

Integer是具有静态方法的原始数据类型的包装类。 它可以用作需要对象的方法的参数,而 int 可以用作需要整数值的方法的参数,可用于算术表达式。

例如:

Integer number = new Integer(5);

An int and Integer in Java and C# are two different terms used to represent different things. It is one of the the primitive data types that can be assigned to a variable that can store exactly. One value of its declared type at a time.

For example:

int number = 7;

Where int is the datatype assigned to the variable number which holds the value seven. So an int is just a primitive not an object.

While an Integer is a wrapper class for a primitive data type which has static methods. That can be used as an argument to a method which requires an object, where as int can be used as an argument to a method which requires an integer value, that can be used for arithmetic expression.

For example:

Integer number = new Integer(5);
淑女气质 2024-07-10 23:54:38

在这两种语言(Java 和 C#)中,int 是 4 字节有符号整数。

与 Java 不同,C# 提供有符号和无符号整数值。 由于 Java 和 C# 是面向对象的,这些语言中的某些操作不会直接映射到运行时提供的指令,因此需要定义为某种类型的对象的一部分。

C# 提供了 System.Int32,它是一种值类型,使用属于堆上引用类型的部分内存。

java 提供了java.lang.Integer,它是在int 上操作的引用类型。 Integer 中的方法不能直接编译为运行时指令。因此,我们将 int 值装箱以将其转换为 Integer 实例,并使用需要某种类型实例的方法(例如 toString()、parseInt()valueOf() 等)。

在 C# 中,变量 int 指的是 System.Int32.Any 内存中的 4 字节值可以解释为原始 int,可以通过 System.Int32 的实例进行操作。因此 int 是 < code>System.Int32.When 使用与整数相关的方法,例如 int.Parse()int.ToString() 等。 Integer 被编译到 FCL 中System.Int32 结构调用相应的方法,例如 Int32.Parse()Int32.ToString()

In both languages (Java and C#) int is 4-byte signed integer.

Unlike Java, C# Provides both signed and unsigned integer values. As Java and C# are object object-oriented, some operations in these languages do not map directly onto instructions provided by the run time and so needs to be defined as part of an object of some type.

C# provides System.Int32 which is a value type using a part of memory that belongs to the reference type on the heap.

java provides java.lang.Integer which is a reference type operating on int. The methods in Integer can't be compiled directly to run time instructions.So we box an int value to convert it into an instance of Integer and use the methods which expects instance of some type (like toString(), parseInt(), valueOf() etc).

In C# variable int refers to System.Int32.Any 4-byte value in memory can be interpreted as a primitive int, that can be manipulated by instance of System.Int32.So int is an alias for System.Int32.When using integer-related methods like int.Parse(), int.ToString() etc. Integer is compiled into the FCL System.Int32 struct calling the respective methods like Int32.Parse(), Int32.ToString().

铜锣湾横着走 2024-07-10 23:54:37

在 Java 等平台中,int 是基元,而 Integer 是保存整数字段的对象。 重要的区别是原语总是按值传递,并且根据定义是不可变的。

任何涉及原始变量的操作总是返回一个新值。 另一方面,对象是通过引用传递的。 有人可能会争辩说,对象的指向(又名引用)也是通过值传递的,但内容却不是。

In platforms like Java, ints are primitives while Integer is an object which holds a integer field. The important distinction is that primitives are always passed around by value and by definition are immutable.

Any operation involving a primitive variable always returns a new value. On the other hand, objects are passed around by reference. One could argue that the point to the object (AKA the reference) is also being passed around by value, but the contents are not.

梦幻之岛 2024-07-10 23:54:37

您以前编程过吗? (int) 是您可以为变量设置的基本类型之一(就像 char、float 等)。

但 Integer 是一个包装类,您可以使用它对 int 变量执行一些函数(例如将其转换为字符串,反之亦然,...),但请注意包装类中的方法是静态的,因此您可以使用它们随时无需创建 Integer 类的实例。
回顾一下:

int x;
Integer y; 

x 和 y 都是 int 类型的变量,但 y 由 Integer 类包装,并且有多种您使用的方法,但如果您需要调用 Integer 包装类的一些函数,您可以简单地做到这一点。

Integer.toString(x);

但请注意,x 和 y 都是正确的,但如果您想将它们用作基本类型,请使用简单形式(用于定义 x)。

have you ever programmed before then (int) is one of the primitive types you can set for your variables (just like char, float, ...).

but Integer is a wrapper class that you can use it to do some functions on an int variable (e.g convert it to string or vise versa,...) , but keep note that methods in the wrapper classes are static so you can use them anytime without creating an instance of Integer class.
as a recap :

int x;
Integer y; 

x and y are both variables of type int but y is wrapped by an Integer class and has several methods that you use,but i case you need to call some functions of Integer wrapper class you can do it simply.

Integer.toString(x);

but be aware that both x and y are corect but if you want to use them just as a primitive type, use the simple form (used for defining x).

生来就爱笑 2024-07-10 23:54:37

int 变量保存 32 位有符号整数值。 Integer(大写 I)保存对(类)类型 Integer 的对象或 null 的引用。

Java 自动在两者之间进行转换; 每当 Integer 对象作为 int 运算符的参数出现或分配给 int 变量,或者将 int 值分配给 Integer 变量时,从 Integer 到 int。 这种铸造称为装箱/拆箱。

如果引用 null 的 Integer 变量被显式或隐式取消装箱,则会引发 NullPointerException。

An int variable holds a 32 bit signed integer value. An Integer (with capital I) holds a reference to an object of (class) type Integer, or to null.

Java automatically casts between the two; from Integer to int whenever the Integer object occurs as an argument to an int operator or is assigned to an int variable, or an int value is assigned to an Integer variable. This casting is called boxing/unboxing.

If an Integer variable referencing null is unboxed, explicitly or implicitly, a NullPointerException is thrown.

流星番茄 2024-07-10 23:54:37

Java:

intdoublelongbytefloat< /code>、doubleshortbooleanchar - 基元。 用于保存基本数据类型
语言支持。 原始类型不属于
对象层次结构,并且它们不继承Object。 它们可以通过引用方法来传递。

双精度型浮点型长整型整数短型字节< /code>、CharacterBoolean 是类型 Wrappers,封装在 java.lang 中。 所有数字类型包装器都定义了构造函数,允许从给定值或该值的字符串表示形式构造对象。
即使是最简单的计算,使用对象也会增加开销。

从 JDK 5 开始,Java 包含了两个非常有用的功能:自动装箱和自动拆箱。 自动装箱/拆箱极大地简化和简化了必须将基本类型转换为对象的代码,反之亦然。

构造函数示例:

Integer(int num)
Integer(String str) throws NumberFormatException
Double(double num)
Double(String str) throws NumberFormatException

装箱/拆箱示例:

class ManualBoxing {
        public static void main(String args[]) {
        Integer objInt = new Integer(20);  // Manually box the value 20.
        int i = objInt.intValue();  // Manually unbox the value 20
        System.out.println(i + " " + iOb); // displays 20 20
    }
}

自动装箱/自动拆箱示例:

class AutoBoxing {
    public static void main(String args[]) {
        Integer objInt = 40; // autobox an int
        int i = objInt ; // auto-unbox
        System.out.println(i + " " + iOb); // displays 40 40
    }
}

PS Herbert Schildt 的书作为参考。

Java:

int, double, long, byte, float, double, short, boolean, char - primitives. Used for hold the basic data types
supported by the language. the primitive types are not part of the
object hierarchy, and they do not inherit Object. Thet can'be pass by reference to a method.

Double, Float, Long, Integer, Short, Byte, Character, and Boolean, are type Wrappers, packaged in java.lang. All of the numeric type wrappers define constructors that allow an object to be constructed from a given value, or a string representation of that value.
Using objects can add an overhead to even the simplest of calculations.

Beginning with JDK 5, Java has included two very helpful features: autoboxing and autounboxing. Autoboxing/unboxing greatly simplifies and streamlines code that must convert primitive types into objects, and vice versa.

Example of constructors:

Integer(int num)
Integer(String str) throws NumberFormatException
Double(double num)
Double(String str) throws NumberFormatException

Example of boxing/unboxing:

class ManualBoxing {
        public static void main(String args[]) {
        Integer objInt = new Integer(20);  // Manually box the value 20.
        int i = objInt.intValue();  // Manually unbox the value 20
        System.out.println(i + " " + iOb); // displays 20 20
    }
}

Example of autoboxing/autounboxing:

class AutoBoxing {
    public static void main(String args[]) {
        Integer objInt = 40; // autobox an int
        int i = objInt ; // auto-unbox
        System.out.println(i + " " + iOb); // displays 40 40
    }
}

P.S. Herbert Schildt's book was taken as a reference.

别再吹冷风 2024-07-10 23:54:36

int 用于声明原始变量

e.g. int i=10;

Integer 用于创建 Integer 类的引用变量

Integer a = new Integer();

int is used to declare primitive variable

e.g. int i=10;

Integer is used to create reference variable of class Integer

Integer a = new Integer();
殤城〤 2024-07-10 23:54:36

我在之前的答案中没有看到的另一件事:
在 Java 中,像 Integer、Double、Float、Boolean... 和 String 这样的原始包装类应该是不变的,因此当您传递这些类的实例时,调用的方法不能以任何方式更改您的数据,相反与大多数其他类一样,其内部数据可以通过其公共方法更改。 因此,除了构造函数之外,此类只有“getter”方法,没有“setter”。

在java程序中,字符串文字存储在堆内存的单独部分中,仅存储文字的一个实例,以节省内存重用这些实例

One more thing that I don't see in previous answers:
In Java the primitive wrappers classes like Integer, Double, Float, Boolean... and String are suposed to be invariant, so that when you pass an instance of those classes the invoked method couldn't alter your data in any way, in opositión with most of other classes, which internal data could be altered by its public methods. So that this classes only has 'getter' methods, no 'setters', besides the constructor.

In a java program String literals are stored in a separate portion of heap memory, only a instance for literal, to save memory reusing those instances

暖树树初阳… 2024-07-10 23:54:36

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;
}

This has already been answered for Java, here's the C# answer:

"Integer" is not a valid type name in C# and "int" is just an alias for System.Int32. Also, unlike in Java (or C++) there aren't any special primitive types in C#, every instance of a type in C# (including int) is an object. Here's some demonstrative code:

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;
}
独﹏钓一江月 2024-07-10 23:54:35

关于 Java 1.5 和 自动装箱 在比较 Integer 时有一个重要的“怪癖”对象。

在 Java 中,值为 -128 到 127 的 Integer 对象是不可变的(也就是说,对于一个特定的整数值,比如 23,通过程序实例化的所有值为 23 的 Integer 对象都指向完全相同的值)目的)。

例如,这返回 true:

Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1 == i2); //  true

而这返回 false:

Integer i1 = new Integer(128);
Integer i2 = new Integer(128);
System.out.println(i1 == i2); //  false

== 通过引用进行比较(变量是否指向同一个对象)。

此结果可能会有所不同,也可能不会有所不同,具体取决于您使用的 JVM。 Java 1.5 的自动装箱规范要求整数(-128 到 127)始终装箱到同一个包装器对象。

一个办法? =) 比较 Integer 对象时应始终使用 Integer.equals() 方法。

System.out.println(i1.equals(i2)); //  true

更多信息请参见 java.net 示例位于 < a href="http://bexhuff.com/2006/11/java-1-5-autoboxing-wackyness" rel="noreferrer">bexhuff.com

Regarding Java 1.5 and autoboxing there is an important "quirk" that comes to play when comparing Integer objects.

In Java, Integer objects with the values -128 to 127 are immutable (that is, for one particular integer value, say 23, all Integer objects instantiated through your program with the value 23 points to the exact same object).

Example, this returns true:

Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1 == i2); //  true

While this returns false:

Integer i1 = new Integer(128);
Integer i2 = new Integer(128);
System.out.println(i1 == i2); //  false

The == compares by reference (does the variables point to the same object).

This result may or may not differ depending on what JVM you are using. The specification autoboxing for Java 1.5 requires that integers (-128 to 127) always box to the same wrapper object.

A solution? =) One should always use the Integer.equals() method when comparing Integer objects.

System.out.println(i1.equals(i2)); //  true

More info at java.net Example at bexhuff.com

一袭白衣梦中忆 2024-07-10 23:54:35

在 Java 中, JVM< 中有两种基本类型/a>. 1) 原始类型和 2) 引用类型。 int 是原始类型,Integer 是类类型(这是一种引用类型)。

原始值不与其他原始值共享状态。 类型为原始类型的变量始终保存该类型的原始值。

int aNumber = 4;
int anotherNum = aNumber;
aNumber += 6;
System.out.println(anotherNum); // Prints 4

对象是动态创建的类实例或数组。 引用值(通常只是引用)是指向这些对象的指针和一个特殊的空引用,它不引用任何对象。 同一对象可能有多个引用。

Integer aNumber = Integer.valueOf(4);
Integer anotherNumber = aNumber; // anotherNumber references the 
                                 // same object as aNumber

同样在 Java 中,一切都是按值传递的。 对于对象,传递的值是对该对象的引用。 所以java中int和Integer的另一个区别是它们在方法调用中的传递方式。 例如,在

public int add(int a, int b) {
    return a + b;
}
final int two = 2;
int sum = add(1, two);

变量 two 中作为原始整数类型 2 传递。而在

public int add(Integer a, Integer b) {
    return a.intValue() + b.intValue();
}
final Integer two = Integer.valueOf(2);
int sum = add(Integer.valueOf(1), two);

变量 two 中作为对保存整数值 2 的对象的引用传递。


@狼人龙:
通过引用传递的工作方式如下:

public void increment(int x) {
  x = x + 1;
}
int a = 1;
increment(a);
// a is now 2

当调用增量时,它将引用(指针)传递给变量a。 而increment函数直接修改变量a

对于对象类型,它的工作原理如下:

public void increment(Integer x) {
  x = Integer.valueOf(x.intValue() + 1);
}
Integer a = Integer.valueOf(1);
increment(a);
// a is now 2

你现在看到区别了吗?

In Java there are two basic types in the JVM. 1) Primitive types and 2) Reference Types. int is a primitive type and Integer is a class type (which is kind of reference type).

Primitive values do not share state with other primitive values. A variable whose type is a primitive type always holds a primitive value of that type.

int aNumber = 4;
int anotherNum = aNumber;
aNumber += 6;
System.out.println(anotherNum); // Prints 4

An object is a dynamically created class instance or an array. The reference values (often just references) are pointers to these objects and a special null reference, which refers to no object. There may be many references to the same object.

Integer aNumber = Integer.valueOf(4);
Integer anotherNumber = aNumber; // anotherNumber references the 
                                 // same object as aNumber

Also in Java everything is passed by value. With objects the value that is passed is the reference to the object. So another difference between int and Integer in java is how they are passed in method calls. For example in

public int add(int a, int b) {
    return a + b;
}
final int two = 2;
int sum = add(1, two);

The variable two is passed as the primitive integer type 2. Whereas in

public int add(Integer a, Integer b) {
    return a.intValue() + b.intValue();
}
final Integer two = Integer.valueOf(2);
int sum = add(Integer.valueOf(1), two);

The variable two is passed as a reference to an object that holds the integer value 2.


@WolfmanDragon:
Pass by reference would work like so:

public void increment(int x) {
  x = x + 1;
}
int a = 1;
increment(a);
// a is now 2

When increment is called it passes a reference (pointer) to variable a. And the increment function directly modifies variable a.

And for object types it would work as follows:

public void increment(Integer x) {
  x = Integer.valueOf(x.intValue() + 1);
}
Integer a = Integer.valueOf(1);
increment(a);
// a is now 2

Do you see the difference now?

用心笑 2024-07-10 23:54:35

在 C# 中,int 只是 System.Int32别名System.String 的字符串,System.String 的 double,< code>System.Double 等...

我个人更喜欢 int、string、double 等,因为它们不需要 using System; 语句:) 我知道这是一个愚蠢的原因...

In C#, int is just an alias for System.Int32, string for System.String, double for System.Double etc...

Personally I prefer int, string, double, etc. because they don't require a using System; statement :) A silly reason, I know...

孤檠 2024-07-10 23:54:35

使用包装类的原因有很多:

  1. 我们可以获得额外的行为(例如我们可以使用方法)
  2. 我们可以存储空值,而在基元中我们不能
  3. 集合支持存储对象而不是基元。

There are many reasons to use wrapper classes:

  1. We get extra behavior (for instance we can use methods)
  2. We can store null values whereas in primitives we cannot
  3. Collections support storing objects and not primitives.
浮生面具三千个 2024-07-10 23:54:34

我将在这里发帖,因为其他一些帖子与 C# 的关系稍微不准确。

正确: intSystem.Int32 的别名。
错误: float 不是 System.Float 的别名,而是 System.Single

基本上, int 是一个C# 编程语言中的保留关键字,是 System.Int32 值类型的别名。

然而,float 和 Float 并不相同,因为“float”的正确系统类型是 System.Single。 有一些像这样的类型具有似乎与类型名称不直接匹配的保留关键字。

在 C# 中,“int”和“System.Int32”或任何其他对或关键字/系统类型之间没有区别,除非定义枚举。 使用枚举,您可以指定要使用的存储大小,在这种情况下,您只能使用保留关键字,而不能使用系统运行时类型名称。

int 中的值是否存储在堆栈、内存中或作为引用的堆对象取决于上下文以及您如何使用它。

方法中的此声明:

int i;

定义一个 System.Int32 类型的变量 i,该变量位于寄存器或堆栈中,具体取决于优化。 类型(结构或类)中的相同声明定义成员字段。 方法参数列表中的相同声明定义了一个参数,其存储选项与局部变量相同。 (请注意,如果您开始将迭代器方法混合在一起,则本段无效,这些完全是不同的野兽)

要获取堆对象,您可以使用装箱:

object o = i;

这将创建 i< 内容的装箱副本/code> 在堆上。 在 IL 中,您可以直接访问堆对象上的方法,但在 C# 中,您需要将其强制转换回 int,这将创建另一个副本。 因此,在 C# 中,如果不创建新 int 值的新装箱副本,则无法轻松更改堆上的对象。 (呃,这一段读起来不太容易。)

I'll just post here since some of the other posts are slightly inaccurate in relation to C#.

Correct: int is an alias for System.Int32.
Wrong: float is not an alias for System.Float, but for System.Single

Basically, int is a reserved keyword in the C# programming language, and is an alias for the System.Int32 value type.

float and Float is not the same however, as the right system type for ''float'' is System.Single. There are some types like this that has reserved keywords that doesn't seem to match the type names directly.

In C# there is no difference between ''int'' and ''System.Int32'', or any of the other pairs or keywords/system types, except for when defining enums. With enums you can specify the storage size to use and in this case you can only use the reserved keyword, and not the system runtime type name.

Wether the value in the int will be stored on the stack, in memory, or as a referenced heap object depends on the context and how you use it.

This declaration in a method:

int i;

defines a variable i of type System.Int32, living in a register or on the stack, depending on optimizations. The same declaration in a type (struct or class) defines a member field. The same declaration in a method argument list defines a parameter, with the same storage options as for a local variable. (note that this paragraph is not valid if you start pulling iterator methods into the mix, these are different beasts altogether)

To get a heap object, you can use boxing:

object o = i;

this will create a boxed copy of the contents of i on the heap. In IL you can access methods on the heap object directly, but in C# you need to cast it back to an int, which will create another copy. Thus, the object on the heap cannot easily be changed in C# without creating a new boxed copy of a new int value. (Ugh, this paragraph doesn't read all that easily.)

梦回旧景 2024-07-10 23:54:34

我将补充上面给出的出色答案,并讨论装箱和拆箱,以及这如何应用于 Java(尽管 C# 也有)。 我将仅使用 Java 术语,因为我对此更加熟悉。

正如答案所提到的, int 只是一个数字(称为 unboxed 类型),而 Integer 是一个对象(包含数字,因此盒装类型)。 用 Java 术语来说,这意味着(除了无法调用 int 上的方法之外),您不能在集合中存储 int 或其他非对象类型(List地图等)。 为了存储它们,您必须首先将它们装入相应的盒装类型中。

Java 5 及以后的版本具有称为“自动装箱”和“自动拆箱”的功能,它们允许在幕后完成装箱/拆箱。 比较和对比: Java 5 版本:

Deque<Integer> queue;

void add(int n) {
    queue.add(n);
}

int remove() {
    return queue.remove();
}

Java 1.4 或更早版本(也没有泛型):

Deque queue;

void add(int n) {
    queue.add(Integer.valueOf(n));
}

int remove() {
    return ((Integer) queue.remove()).intValue();
}

必须注意的是,尽管 Java 5 版本很简洁,但这两个版本都生成相同的字节码。 因此,尽管自动装箱和自动拆箱非常方便,因为您编写的代码较少,但这些操作do发生在幕后,具有相同的运行时成本,因此您仍然必须意识到它们的存在。

希望这可以帮助!

I'll add to the excellent answers given above, and talk about boxing and unboxing, and how this applies to Java (although C# has it too). I'll use just Java terminology because I am more au fait with that.

As the answers mentioned, int is just a number (called the unboxed type), whereas Integer is an object (which contains the number, hence a boxed type). In Java terms, that means (apart from not being able to call methods on int), you cannot store int or other non-object types in collections (List, Map, etc.). In order to store them, you must first box them up in its corresponding boxed type.

Java 5 onwards have something called auto-boxing and auto-unboxing which allow the boxing/unboxing to be done behind the scenes. Compare and contrast: Java 5 version:

Deque<Integer> queue;

void add(int n) {
    queue.add(n);
}

int remove() {
    return queue.remove();
}

Java 1.4 or earlier (no generics either):

Deque queue;

void add(int n) {
    queue.add(Integer.valueOf(n));
}

int remove() {
    return ((Integer) queue.remove()).intValue();
}

It must be noted that despite the brevity in the Java 5 version, both versions generate identical bytecode. Thus, although auto-boxing and auto-unboxing are very convenient because you write less code, these operations do happens behind the scenes, with the same runtime costs, so you still have to be aware of their existence.

Hope this helps!

请远离我 2024-07-10 23:54:34

嗯,在 Java 中,int 是基元,而 Integer 是对象。 意思是,如果你创建了一个新的 Integer:

Integer i = new Integer(6);

你可以在 i: 上调用一些方法,

String s = i.toString();//sets s the string representation of i

而对于 int:

int i = 6;

你不能在它上调用任何方法,因为它只是一个原语。 所以:

String s = i.toString();//will not work!!!

会产生错误,因为 int 不是对象。

int 是 Java 中为数不多的原语之一(还有 char 和其他一些原语)。 我不是 100% 确定,但我认为 Integer 对象或多或少只有一个 int 属性和一大堆与该属性交互的方法(例如 toString() 方法)。 所以 Integer 是一种处理 int 的奇特方式(就像 String 是一种处理一组字符的奇特方式一样)。

我知道 Java 不是 C,但由于我从未用 C 编程过,所以这是我能得到的最接近的答案。

整数对象 javadoc

整数对象与 int 基元比较

Well, in Java an int is a primitive while an Integer is an Object. Meaning, if you made a new Integer:

Integer i = new Integer(6);

You could call some method on i:

String s = i.toString();//sets s the string representation of i

Whereas with an int:

int i = 6;

You cannot call any methods on it, because it is simply a primitive. So:

String s = i.toString();//will not work!!!

would produce an error, because int is not an object.

int is one of the few primitives in Java (along with char and some others). I'm not 100% sure, but I'm thinking that the Integer object more or less just has an int property and a whole bunch of methods to interact with that property (like the toString() method for example). So Integer is a fancy way to work with an int (Just as perhaps String is a fancy way to work with a group of chars).

I know that Java isn't C, but since I've never programmed in C this is the closest I could come to the answer.

Integer object javadoc

Integer Ojbect vs. int primitive comparison

泛滥成性 2024-07-10 23:54:33

在 Java 中,“int”类型是基元,而“Integer”类型是对象。

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


对象和基元之间的差异在某种程度上超出了这个问题的范围,但总结一下:

对象提供多态性的设施,通过引用传递(或更准确地说,通过值传递引用),并分配来自。 相反,基元是按值传递的不可变类型,通常从 堆栈

In Java, the 'int' type is a primitive, whereas the 'Integer' type is an object.

In C#, the 'int' type is the same as System.Int32 and is a value type (ie more like the java 'int'). An integer (just like any other value types) can be boxed ("wrapped") into an object.


The differences between objects and primitives are somewhat beyond the scope of this question, but to summarize:

Objects provide facilities for polymorphism, are passed by reference (or more accurately have references passed by value), and are allocated from the heap. Conversely, primitives are immutable types that are passed by value and are often allocated from the stack.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文