当结构实例具有“引用类型”属性时会发生什么?
当结构数据类型具有引用类型的属性时,它如何仍然是值类型?
它实际上是一个以某种方式用值类型行为处理的引用类型吗?
How the struct data-type can still be a value type when it has a property that is Reference Type?
Is it in real a reference type which is somehow processed with a value type behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这很简单,真的。结构中的字段仅包含对引用类型对象的引用。如果您熟悉 C 或 C++ 等其他语言,您可能会立即意识到它与“指针”类似,它本质上是一个包含“指向”对象所在内存地址的值。
它不会消耗更多内存,因为该结构仅存储对对象的引用,而不是对象的完整副本。当不再有对该对象的任何引用时,它将有资格进行垃圾回收。
您可能会认为这类似于“按值”传递引用对象的方式。在 VB.NET 中,这是通过使用
ByVal
关键字明确指示的。在 C# 中,按值传递对象只是默认设置,您必须使用ref
明确表明您希望通过引用传递它们。无论哪种方式,要点是引用对象仍然可以“按值”传递,因为传递的只是引用的副本,而不是整个对象的副本。当然,像 .NET 这样的托管环境的好处之一是您不必担心任何这些实现细节。如果您有一个包含表示值类型和引用类型的字段的结构,您的代码将正常工作。
另请参阅我对这个非常相似的问题的回答: 使用引用类型成员定义结构体有意义吗? 首先值得考虑的是您是否真的需要定义结构体。大多数时候,上课是更好的选择。但无论您选择哪一种,包含引用类型的字段的行为都是相同的。
It's simple, really. The field in the struct simply contains a reference to the object that is a reference type. If you're familiar with other languages like C or C++, you might recognize this immediately as being similar to a "pointer", which is essentially a value containing the memory address at which the object being "pointed to" resides.
It doesn't consume any more memory because the struct is only storing a reference to the object, not a complete copy of the object. And when there are no longer any references to that object, it will become eligible for garbage collection.
You might think of this as being similar to how a reference object can be passed "by value". In VB.NET, this is explicitly indicated with the use of the
ByVal
keyword. In C#, passing objects by value is simply the default, and you have to indicate explicitly that you want them passed by reference usingref
. Either way, the point is that a reference object can still be passed "by value" because all that's being passed is a copy of the reference, not a copy of the entire object.Of course, one of the joys of managed environments like .NET is that you don't have to worry about any of these implementation details. Your code will work just fine if you have a struct containing fields that represent both value types and reference types.
Also see my answer to this very similar question: Does it make sense to define a struct with a reference type member? It's worth considering whether or not you really need to define a struct in the first place. Most of the time, a class is a better choice. But whichever one you choose, the behavior in terms of fields containing reference types will be the same.