我定义了两个引用结构的变量:ref var x = ref struct_var。它们一开始并不相等,就像打印出来的结果一样。当我使用x=y将它们设置为相同时,它们似乎通常指向相同的对象。但是在我修改了它们的成员值之后,它们并没有同步。我有没有忽略任何语法特征?
struct d { public int x, y; };
static void Main(string[] args)
{
var arr = new[] { new d() { x = 1, y = 2 }, new d() { x = 3, y = 4 } };
ref var x = ref arr[0];
ref var y = ref arr[1];
print(x.GetHashCode() == y.GetHashCode(), object.Equals(x, y)); // false, false
x = y; // it seem they ref to the same struct.
print(x.GetHashCode() == y.GetHashCode(), object.Equals(x, y)); // true, true
x.x = ~y.y; // x.x is not equal to y.x
print(x.GetHashCode() == y.GetHashCode(), object.Equals(x, y)); // false, false
y.x = x.x; //
print(x.GetHashCode() == y.GetHashCode(), object.Equals(x, y)); // true, true
}发布于 2021-01-21 15:43:06
x = y不做引用赋值,它复制值。您需要使用
x = ref y;它给出了您期望的结果:
struct d { public int x, y; }
static void Main(string[] args)
{
var arr = new[] { new d{ x = 1, y = 2 }, new d{ x = 3, y = 4 } };
ref var x = ref arr[0];
ref var y = ref arr[1];
(x.Equals(y)).Dump(); // False
x = ref y;
(x.Equals(y)).Dump(); // True
x.x = ~y.y;
(x.Equals(y)).Dump(); // True
y.x = x.x; //
(x.Equals(y)).Dump(); // True
}arr现在包含(1, 2), (-5, 4)。
https://stackoverflow.com/questions/65822253
复制相似问题