How to assign a C# struct to another struct?
To assign one structure to another, you can use the assignment operator (=) or pass by reference.
Here is an example of using assignment operators:
struct MyStruct
{
public int Value;
}
// 创建一个结构体对象
MyStruct struct1;
struct1.Value = 10;
// 将struct1赋值给struct2
MyStruct struct2 = struct1;
// 输出结果
Console.WriteLine(struct2.Value); // 输出 10
In the example above, by assigning struct1 to struct2, the Value member in struct2 is given the same value as struct1.
Here is an example of assignment by reference:
struct MyStruct
{
public int Value;
}
// 创建一个结构体对象
MyStruct struct1;
struct1.Value = 10;
// 通过引用传递,将struct1的值赋给struct2
ref MyStruct struct2 = ref struct1;
// 修改struct1的值
struct1.Value = 20;
// 输出结果
Console.WriteLine(struct2.Value); // 输出 20
In this example, by passing a reference of struct1 to struct2 using the ref keyword, it means that struct2 points to the same memory location as struct1. Therefore, when we modify the value of struct1, the value of struct2 will also change accordingly.