struct
是 C# 中的值类型。当我们将 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
}
}
是的。一般来说,尽管制作如此复杂的结构可能是一个坏主意 - 它们通常应该只包含几个简单的值。如果结构内有结构,则可能需要考虑引用类型是否更合适。
关于c# - 复制包含另一个结构的结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3302944/