gpt4 book ai didi

c# - 动态类型和值类型如何工作?

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:58 29 4
gpt4 key购买 nike

有一小段代码看不懂:

class Program
{
static void Main(string[] args)
{
var ts = new TestStruct() { a = 2 };
object ots = ts;
dynamic dts = ots;
ts.a = 6;
dts.a = 4;
Console.WriteLine(dts.GetType()); //Type is TestStruct
Console.WriteLine("ts.a =" + ts.a); //6
Console.WriteLine("unboxed ts.a =" + ((TestStruct)ots).a); //4
Console.WriteLine("dts.a =" + dts.a); //4
Console.ReadKey();
}
}

public struct TestStruct
{
public int a;
}

dtsots 引用堆上的同一个变量,但是 GetType 返回 dts 测试结构dtsTestStruct 但存储在堆上?或者我不明白的地方?

最佳答案

长话短说:

dtsots 指向相同的、盒装的 ts 副本。 ts 单独包含原始的TestStruct


如您所知,Boxing and unboxing像这样工作:

A key difference from the same operations on class types is that boxing and unboxing copies the struct value either into or out of the boxed instance. Thus, following a boxing or unboxing operation, changes made to the unboxed struct are not reflected in the boxed struct.

所以在这一行中:

object ots = ts;

您实际上是在复制您的struct,它变成了一个引用类型。您现在有两个 TestStruct 实例。上,原始 ts,第二个,副本,也是引用类型(盒装 TestStruct)。因此,在这一行之后:

dynamic dts = ots;

ts 的盒装副本由两个引用指向:otsdtsdtsdynamic 的事实在这里无关紧要。什么dynamic确实,只是将类型检查推迟到运行时,在此之后,它的行为就像 object:

The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time. As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.

在调试器中逐步执行代码并检查 ts.GetHashCode()ots.GetHashCode()dts.GetHashCode()。实际复制可能不会立即发生,而是在您修改结构后发生。

关于c# - 动态类型和值类型如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26202194/

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