好奇心:将C#结构转换为对象仍然会复制它 [英] Curiosity: Converting a C# struct into an object still copies it
问题描述
这个问题更多是出于好奇心而不是真正的问题。考虑下面的代码(C#4.0,如果重要):
This question is more out of curiosity than a real problem. Consider the following code (C# 4.0, if it matters):
class Program {
static Point myPoint = new Point(3, 5);
static void Main(string[] args) {
Console.WriteLine("Point Struct Before: " + myPoint);
object point = GetPoint();
Console.WriteLine("Point Object Before: " + point);
myPoint.X = 10;
Console.WriteLine("Point Struct After: " + myPoint);
Console.WriteLine("Point Object After: " + point);
}
static object GetPoint() {
return myPoint;
}
}
这会输出以下结果:
Point Struct Before: 3;5
Point Object Before: 3;5
Point Struct After: 10;5
Point Object After: 3;5
现在,这是正常工作, 正在复制GetPoint()
,而不是引用。 (否则最后一行也会读为10; 5。)
Now, this works as it should, meaning the point returned by GetPoint()
is being copied rather than referenced. (Otherwise the last line would also have read "10;5".)
我的问题是:为什么这样工作?编译器如何知道是否复制或引用一个对象?这是否意味着此决定是在运行时而不是在编译期间完成的?
My question now is: Why does this work? How does the compiler know whether to copy or reference an object? Does this mean that this decision is done during runtime rather than during compilation?
此外,现在允许我设置 point
到 null
,而 struct
s不能设置为 null
。
Also, this now allows me to set point
to null
whereas struct
s can't be set to null
. Is the struct automatically converted into a nullable type?
推荐答案
您正在观察被称为拳击。它本质上是将值类型转换为引用类型。
You are observing the process called boxing. It essentially converts a value type into a reference type.
这篇关于好奇心:将C#结构转换为对象仍然会复制它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!