gpt4 book ai didi

通过引用传递结构时 C# 框或副本?

转载 作者:行者123 更新时间:2023-12-05 01:19:13 24 4
gpt4 key购买 nike

C# 是否在此处装箱结构?

struct S { int x; }

void foo(ref S s) { s.x = 1; }

main {
var s = new S();
foo(ref s); <-- boxing??
}

我在类中听说过关于结构的奇怪内容。这里有拳击吗?这是传递成员(member)的副本吗?

class C { S s; }

main {
var c = new C();
foo(ref c.s); <-- boxing here?? copy here???
}
void foo(ref S s) { s.x = 1; }

最佳答案

如果你阅读ref的文档,那么Struct就是值类型

Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is NO boxing of a value type when it is passed by reference.

ref (C# Reference)

这里解释 ref 到底在做什么。

The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the called method is reflected in the calling method.

关于通过引用传递结构时 C# 框或副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40774873/

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