值类型和引用类型整数之间的差异。 [英] Difference between value typeand reference type integer.

查看:81
本文介绍了值类型和引用类型整数之间的差异。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我曾经认为引用类型不能包含valuetype .....请帮助。

question-

如果int a = 15是值类型。并且

int b = new int()是引用类型。

那么为什么b = a被允许????





请帮助。

解决方案

  int  b =  new   int (); 

不创建引用类型 - 它创建一个值类型。 int 始终是一个值类型, new int()语法只允许完成,它不会创建任何堆上的新分配,并且不返回引用。

如果您查看IL,它会生成相同的代码:

  int  A =  new   int () ; 
int B = 0 ;



。locals init([0] int32 A,
[1] int32 B)
IL_0000:nop
IL_0001:ldc.i4.0
IL_0002:stloc.0
IL_0003:ldc.i4.0
IL_0004:stloc.1


int b = new int()不是引用类型,它与说 int b = 0; 正好相同因为使用 new 运算符并不意味着您获得了引用类型。

话虽如此, int [] b = new int [10] 确实导致数组对象本身的引用类型,但每个成员仍然是价值类型。



有关更好的解释,请参阅 MSDN文档 [ ^ ]。

MSDN:值类型 [ ^ ]

Hi,

I used to think that reference type cannot contain valuetype.....Please help.
question-
if int a=15 is value type. and
int b=new int() is reference type.
Then why b=a is allowed????


Please help.

解决方案

int b=new int();

Does not create a reference type - it creates a value type. int is always a value type, the new int() syntax is just allowed for completion, it does not create any new allocation on the heap, and does not return a reference.
If you have a look at the IL it generates the same code:

int A = new int();
int B = 0;


.locals init ([0] int32 A,
              [1] int32 B)
IL_0000:  nop
IL_0001:  ldc.i4.0
IL_0002:  stloc.0
IL_0003:  ldc.i4.0
IL_0004:  stloc.1


int b = new int() is not a reference type, it is the same as saying int b = 0; Just because the new operator is used does not mean you are getting a reference type.
That being said, int[] b = new int[10] does result in a reference type on the array object itself, but each of the members are still value types.

For a better explanation, see MSDN Documentation here[^].
MSDN: Value Types[^]


这篇关于值类型和引用类型整数之间的差异。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆