我如何通过“引用"分配到 C# 中的类字段? [英] How do I assign by "reference" to a class field in c#?

查看:24
本文介绍了我如何通过“引用"分配到 C# 中的类字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解如何通过引用"分配给 c# 中的类字段.

I am trying to understand how to assign by "reference" to a class field in c#.

我需要考虑以下示例:

 public class X
 {

  public X()
  {

   string example = "X";

   new Y( ref example );

   new Z( ref example );

   System.Diagnostics.Debug.WriteLine( example );

  }

 }

 public class Y
 {

  public Y( ref string example )
  {
   example += " (Updated By Y)";
  }

 }

 public class Z
 {

  private string _Example;

  public Z( ref string example )
  {

   this._Example = example;

   this._Example += " (Updated By Z)";

  }

 }

 var x = new X();

运行上述代码时,输​​出为:

When running the above code the output is:

X(由 Y 更新)

而不是:

X(由 Y 更新)(由 Z 更新)

X (Updated By Y) (Updated By Z)

正如我所希望的.

似乎将引用参数"分配给字段会丢失引用.

It seems that assigning a "ref parameter" to a field loses the reference.

在分配给字段时,有没有办法保持引用?

Is there any way to keep hold of the reference when assigning to a field?

谢谢.

推荐答案

没有.ref 纯粹是一个调用约定.您不能使用它来限定字段.在 Z 中,_Example 被设置为传入的字符串引用的值.然后您使用 += 为其分配一个新的字符串引用.您从不分配给 example,因此 ref 无效.

No. ref is purely a calling convention. You can't use it to qualify a field. In Z, _Example gets set to the value of the string reference passed in. You then assign a new string reference to it using +=. You never assign to example, so the ref has no effect.

您想要的唯一解决方法是拥有一个包含引用(此处为字符串)的共享可变包装器对象(一个数组或假设的 StringWrapper).一般来说,如果你需要这个,你可以找到一个更大的可变对象供类共享.

The only work-around for what you want is to have a shared mutable wrapper object (an array or a hypothetical StringWrapper) that contains the reference (a string here). Generally, if you need this, you can find a larger mutable object for the classes to share.

 public class StringWrapper
 {
   public string s;
   public StringWrapper(string s)
   {
     this.s = s;
   }

   public string ToString()
   {
     return s;
   }
 }

 public class X
 {
  public X()
  {
   StringWrapper example = new StringWrapper("X");
   new Z(example)
   System.Diagnostics.Debug.WriteLine( example );
  }
 }

 public class Z
 {
  private StringWrapper _Example;
  public Z( StringWrapper example )
  {
   this._Example = example;
   this._Example.s += " (Updated By Z)";
  }
 }

这篇关于我如何通过“引用"分配到 C# 中的类字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆