copy struct包含另一个struct

时间:2010-07-21 19:18:16

标签: c# .net

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

的值

2 个答案:

答案 0 :(得分: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
    }
}
  

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

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

答案 1 :(得分:1)

是。这是对的。

相关问题