INT NUM =新INT();该行执行时,会发生什么?发生、INT、NUM

2023-09-04 01:00:09 作者:处对象,我是耐看型,虽然一开始你会觉得我丑,但是看久了就会忍

认识了一个新的东西今天,我们可以通过使用运算符如下

创建整数

  INT NUM =新INT();
 

现在我不知道如果我以这种方式创建一个整数然后将得到的整数将是值类型还是引用类型?我想这将是一个值类型。我想下面的code

  INT NUM1 = 10;
INT NUM2 =新INT();
INT NUM3;
NUM1 = NUM​​2;
NUM2 = NUM​​3;
 

我得到了下面的生成错误:

  

使用未分配的局部变量NUM3的

我知道为什么被赋予此版本错误。但我不知道何时以及如何使用新INT()键,究竟是如何工作的呢?任何人都可以请放些亮呢?

感谢和放大器;问候:)

解决方案

  INT I =新INT();
 
c int Student number is private怎么回事

被equavalent到

  INT I = 0;
 

他们之间没有什么区别。他们会产生相同的 IL 的code在所有。

  // code尺寸4(为0x4)
  .maxstack 1
  .locals的init([0] INT32 NUM)
  IL_0000:NOP
  IL_0001:ldc.i4.0
  IL_0002:stloc.0
  IL_0003:RET
 

使用构造函数(C#编程指南)

  

构造函数的结构类型类似于类的构造函数,但结构   不能包含一个明确的默认构造函数,因为一个是提供   由编译器自动。这个构造函数初始化每个字段   在结构中的默认值

整数默认值为 0 。检查更 默认值表

Got to know a new thing today that we can create integers by using new operator as below

int num = new int();

Now I wonder if I create an integer in this manner then the resulting integer will be a value type or reference type? I guess it will be a value type. I tried the below code

int num1 = 10;
int num2 = new int();
int num3;
num1 = num2;
num2 = num3;

I got the below build error:

Use of unassigned local variable 'num3'

I know why this build error is given. But I wonder when and how to use new int() and how exactly does this work? Can anyone please put some light on this?

Thanks & Regards :)

解决方案

int i = new int();

is equavalent to

int i = 0;

There is no difference between them. They will generate the same IL code at all.

  // Code size       4 (0x4)
  .maxstack  1
  .locals init ([0] int32 num)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  IL_0003:  ret

From Using Constructors (C# Programming Guide)

Constructors for struct types resemble class constructors, but structs cannot contain an explicit default constructor because one is provided automatically by the compiler. This constructor initializes each field in the struct to the default values.

Default value of integers is 0. Check for more Default Values Table

 
精彩推荐
图片推荐