赋值运算符是否指向数据或数据位置? [英] Does the assignment operator point to data or data location?

查看:50
本文介绍了赋值运算符是否指向数据或数据位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的测试,看来当您对控件对象使用赋值运算符时:

From what I have tested, it appears that when you use an assignment operator for a control object:

Panel p = new Panel();
p = Form1.panel1;



即使我已经说过Panel p = new Panel();,为什么p实际上是指向Form1.panel1的指针?为什么p不是全新的控件?

据我了解,这与以下内容明显不同:



p is actually a pointer to Form1.panel1, even though I''ve said Panel p = new Panel(); Why is this? Why is p not a whole new control?

From what I understand, this is markedly different from:

int a = 4;
int b = a;



我很困惑,以至于我什至不知道如何正确地表达这个问题.这是类型还是对象?



I''m quite confused to the point where I don''t even know how to articulate this question properly. Is this a type vs. object thing? Where can I read more about this?

推荐答案

从技术上讲,我认为您是对的,尽管我从未真正考虑过. C#中的对象是引用类型,因此p将是指向为面板的新实例保留的地址的指针.实际上,new运算符确实会创建一个新实例,因此不必担心它=运行时将其全部整理出来.

简单类型是值类型,并包含分配的实际值.唯一需要关注差异的地方就是传递值时.当您将引用类型(例如p)传递给方法时,该方法退出时将保留该方法对其所做的任何更改.当您将值类型传递给方法时,该方法将接收数据的副本,并且在方法退出时,该方法对其所做的更改都会丢失.
Technically, I suppose you''re right, though I''ve never really thought about it. Objects in C# are reference types, so p would be a pointer to the address reserved for the new instance of your panel. The new operator does, in fact, create a new instance, so it isn''t necessary to worry about it = the runtime sorts it all out.

Simple types are value types, and contain actual values assigned. The only time you need to be concerned about the difference is when passing values around. When you pass a reference type, such as p to a method, any changes the method makes to it are retained when the method exits. When you pass a value type to a method, the method receives a copy of the data, and changes made to it by the method are lost when the method exits.


已经说过,请注意结构化类型,即使用关键字struct而不是class声明的结构化类型;它们的工作方式类似于基本类型.
In addition to what Roger already said, be aware of structured types, i.e. the ones declared using the keyword struct instead than class; they works like basic types.


这篇关于赋值运算符是否指向数据或数据位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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