[英]Ref-struct variable assignment and change ineffective in c#
我已經定義了兩個引用結構的變量: ref var x = ref struct_var
。 起初它們並不相等,就像打印出來的結果一樣。 當我使用x=y
將它們設置為相同時,它們似乎通常指向相同的 object。 但是在我修改了它們的成員值之后,它們並沒有同步。 我是否忽略了任何語法特征?
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
}
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)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.