简体   繁体   English

c# 中的 Ref-struct 变量赋值和更改无效

[英]Ref-struct variable assignment and change ineffective in c#

I had defined two variables reference to structs: ref var x = ref struct_var .我已经定义了两个引用结构的变量: ref var x = ref struct_var they were not equal at first, just like the result of the print out.起初它们并不相等,就像打印出来的结果一样。 When I set them to be the same using x=y , they seem to point to the same object generally.当我使用x=y将它们设置为相同时,它们似乎通常指向相同的 object。 But after I modified their member values, they are not synchronized.但是在我修改了它们的成员值之后,它们并没有同步。 Did I overlook any grammatical features?我是否忽略了任何语法特征?

  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 doesn't do a reference assignment, it copies the values. x = y不做参考赋值,它复制值。 You need to use你需要使用

x = ref y;

Which gives the results you expect:这给出了您期望的结果:

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 now contains (1, 2), (-5, 4) . arr现在包含(1, 2), (-5, 4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM