【发布时间】:2021-01-21 06:37:37
【问题描述】:
我定义了两个引用结构的变量: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
}
【问题讨论】:
-
不,
x/y是一个 ref struct 类型,我不能将ref关键字放到x = y。我正在与 2017 年对比。 -
在 VS 2017 中,您需要在项目文件中使用
<LangVersion>7.3</LangVersion>才能启用该功能。 -
@user202729,在我读了两遍答案之后,它确实击中了我的头,很好的答案。谢谢大家。
标签: c#