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