gpt4 book ai didi

c# - 复制包含另一个结构的结构

转载 作者:太空狗 更新时间:2023-10-30 00:21:55 25 4
gpt4 key购买 nike

struct 是 C# 中的值类型。当我们将一个 struct 分配给另一个 struct 变量时,它会复制值。如果那个 struct 包含另一个 struct 怎么样?它会自动复制内部 struct?

的值

最佳答案

是的,会的。下面是一个实际操作示例:

struct Foo
{
public int X;
public Bar B;
}

struct Bar
{
public int Y;
}

public class Program
{
static void Main(string[] args)
{
Foo foo;
foo.X = 1;
foo.B.Y = 2;

// Show that both values are copied.
Foo foo2 = foo;
Console.WriteLine(foo2.X); // Prints 1
Console.WriteLine(foo2.B.Y); // Prints 2

// Show that modifying the copy doesn't change the original.
foo2.B.Y = 3;
Console.WriteLine(foo.B.Y); // Prints 2
Console.WriteLine(foo2.B.Y); // Prints 3
}
}

How about if that struct contains another struct?

是的。一般来说,尽管制作如此复杂的结构可能不是一个好主意——它们通常应该只包含几个简单的值。如果结构内部有结构内部结构,您可能需要考虑引用类型是否更合适。

关于c# - 复制包含另一个结构的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3302944/

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