gpt4 book ai didi

c# - 好奇心 : Converting a C# struct into an object still copies it

转载 作者:太空宇宙 更新时间:2023-11-03 17:11:25 24 4
gpt4 key购买 nike

这个问题更多是出于好奇而不是真正的问题。考虑以下代码(C# 4.0,如果重要的话):

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”。)

我现在的问题是:为什么这样做有效?编译器如何知道是复制还是引用一个对象?这是否意味着该决定是在运行时而不是编译期间完成的?

此外,这现在允许我将 point 设置为 nullstruct 不能设置为 null。结构是否自动转换为可空类型?

最佳答案

Also, this now allows me to set point to null whereas structs can't be set to null. Is the struct automatically converted into a nullable type?

你误解了整个过程:

int i = 5;
object o = i; //Creates a new Int32 with value 5 and assigns it to the object'o' reference storing the value on the garbage collected heap. This is what is called boxing.
object o = null //Simply assigns 'null' to the object reference, it does nothing to the boxed value type 'o' was referencing before.

在上面的示例中,装箱的 int 最终将由 GC 从垃圾收集堆中收集,因为不再有事件引用指向它。

关于c# - 好奇心 : Converting a C# struct into an object still copies it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6304823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com