引用类型,值类型怀疑 [英] Reference type, value type doubt
问题描述
这是一个使我感到困惑的基本问题.
这是示例代码..
This is a basic question which is confusing me..
Here is the sample code..
class Program
{
static void Main(string[] args)
{
c obj = new c();
obj.a = 11;
}
}
class c
{
public int a = 10;
}
现在我的问题是我们知道整数是一个值类型,而类/对象是引用类型..
那么obj.a现在a是引用类型的值类型吗?
因为无需装箱,我们可以直接为obj.a = 11分配一个值,这表明它是一个值类型..但是在引用类型为obj的对象obj下不是"a"吗?
它如何在内部存储?
"a"存储在哪里?
"obj"存储在哪里?
据我所知a应该存储在堆栈中,因为它是值类型,而obj在堆中,因为它是引用类型..但是它们如何关联?堆可以容纳堆栈吗?
Now my question is we know integer is a value type and classes/objects are reference types..
Then obj.a now a is a value type of a reference type ?
since without boxing we can directly assign a value to obj.a = 11 which suggests that it is a value type.. but isn''t "a" under the object obj which is reference type ?
How it is stored internally ?
Where is "a" stored ?
where is "obj" stored?
as far as I know a should be stored in a stack as it is value type and obj in heap as it is reference type.. but how they are associated ? can heap hold stack ? how does it work ?
推荐答案
您对对象和引用类型有了更多的了解.
但是我认为这一声明将消除您的困惑.
"a
的值由通过蓝色打印(类)c
创建的每个object
引用"
对于c
的每个对象,通过分配a
的值将不会直接包含a
的值,而是内容包含a
的引用地址.
因此,这意味着通过更改a
的值将在类c
的每个对象内更改a
的值.
我希望您现在对此有所了解.
You''ve got lot more understanding on Object and reference type.
But I think this one statement will clear your confusion.
"value ofa
is referenced by each ofobject
created from blue print(class)c
"
For every object ofc
by assigning value ofa
will not directly contain value ofa
but rather it content reference address ofa
.
So that mean by changing a value ofa
will change value ofa
inside every object of classc
.
I hope you may have now some idea around.
请在MSDN上阅读此内容,尤其是"ObjectInstance"和"Base Instance Size",这应该消除您的困惑: ^ ]
如果您仍有疑问,请发表评论.
但是请阅读这篇文章.
问候,
Manfred
Please read this on MSDN especially "ObjectInstance" and "Base Instance Size" that should clear you confusion: See How the CLR Creates Runtime Objects
[^]
If you still have some doubts, leave a comment.
But please read this article.
Regards,
Manfred
字段a是值类型,它是c的类定义的一部分. obj.a仍然是值类型.
确切地说,如何在内部存储它是我们在C#中进行开发时往往会忽略的事情.可以想象,它可以在.Net版本之间进行更改.不过,"int a"存储为32位整数.可以使用System.Runtime.InteropServices命名空间中的属性指定值类型的布局.
问候
Espen Harlinn
The field a is a value type that is a part of your class definition for c. obj.a is still a value type.
Exactly how it''s stored internally is something we tend to disregard when we develop in C#. It can conceivably change between .Net versions. The "int a" is stored as a 32-bit integer though. The layout of Value types can be specified using attributes from the System.Runtime.InteropServices namespace.
Regards
Espen Harlinn
这篇关于引用类型,值类型怀疑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!