复制包含另一个结构体的结构体

4

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

2个回答

8
是的,它可以。以下是一个示例,展示了它的应用:
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
    }
}

如果这个结构体包含另一个结构体呢?

是的。一般来说,把这样复杂的结构体放在一起可能不是一个好主意 - 它们通常应该只包含一些简单的值。如果你有嵌套多层结构体的情况,你可能需要考虑使用引用类型。


1

是的,那是正确的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接