问题描述
我想了解如何在C#中引用一类的字段来分配。
I am trying to understand how to assign by "reference" to a class field in c#.
我有以下的例子来考虑:
I have the following example to consider:
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();
在运行上面的code的输出是:
When running the above code the output is:
X(更新者Y)
和不:
X(更新者Y)(更新到Z)
正如我所希望的。
看来,一个字段分配REF参数失去了参考。
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被设置为传递的字符串的参考价值。然后,使用+ =分配一个新的字符串引用。你从来没有分配到的例子,所以裁判没有效果。
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#类字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!