簡體   English   中英

c# 中的 Ref-struct 變量賦值和更改無效

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM