在 C# 中设置对成员字段的引用 [英] Setting a ref to a member field in C#
问题描述
我想为成员字段分配一个引用.但我显然不太了解 C# 的这一部分,因为我失败了 :-) 所以,这是我的代码:
I'd like to assign a reference to a member field. But I obviously do not understand this part of C# very well, because I failed :-) So, here's my code:
public class End {
public string parameter;
public End(ref string parameter) {
this.parameter = parameter;
this.Init();
Console.WriteLine("Inside: {0}", parameter);
}
public void Init() {
this.parameter = "success";
}
}
class MainClass {
public static void Main(string[] args) {
string s = "failed";
End e = new End(ref s);
Console.WriteLine("After: {0}", s);
}
}
输出为:
Inside: failed
After: failed
如何在控制台上获得成功"?
How do I get "success" on the console?
提前致谢,迪杰特拉
推荐答案
这里确实有两个问题.
一个,正如其他海报所说,你不能严格做你想做的事情(就像你可以用 C 和类似的东西).但是 - 行为和意图在 C# 中仍然很容易使用 - 你只需要按照 C# 的方式来做.
One, as the other posters have said, you can't strictly do what you're looking to do (as you may be able to with C and the like). However - the behavior and intent are still readily workable in C# - you just have to do it the C# way.
另一个问题是您尝试使用字符串的不幸尝试 - 正如其他海报中提到的那样 - 不可变 - 并且根据定义被复制.
The other issue is your unfortunate attempt to try and use strings - which are, as one of the other posters mentioned - immutable - and by definition get copied around.
所以,话虽如此,您的代码可以很容易地转换成这样,我认为这确实可以满足您的需求:
So, having said that, your code can easily be converted to this, which I think does do what you want:
public class End
{
public StringBuilder parameter;
public End(StringBuilder parameter)
{
this.parameter = parameter;
this.Init();
Console.WriteLine("Inside: {0}", parameter);
}
public void Init()
{
this.parameter.Clear();
this.parameter.Append("success");
}
}
class MainClass
{
public static void Main(string[] args)
{
StringBuilder s = new StringBuilder("failed");
End e = new End(s);
Console.WriteLine("After: {0}", s);
}
}
这篇关于在 C# 中设置对成员字段的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!