【问题标题】:Ref-struct variable assignment and change ineffective in c#Ref-struct变量赋值和更改在c#中无效
【发布时间】: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#


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 2021-03-18
    • 2014-09-03
    • 2012-08-28
    • 2018-12-04
    • 2017-05-26
    • 2021-05-11
    • 1970-01-01
    • 2022-09-25
    • 1970-01-01
    相关资源
    最近更新 更多