copy struct包含另一个struct

5Yr*_*DBA 4 .net c#

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

Mar*_*ers 9

是的,它会的.这是一个展示它的实例:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果该结构包含另一个结构怎么样?

是.一般来说,虽然制作这样复杂的结构可能是一个坏主意 - 它们通常应该只包含一些简单的值.如果你在结构体内部的结构中有结构,你可能想要考虑引用类型是否更合适.