在构造函数中通过引用传递值,保存它,然后修改它,怎么做?
我如何实现这个功能?我认为它不起作用,因为我将它保存在构造函数中? 我需要做一些装箱/拆箱的胡言乱语吗?
static void Main(string[] args)
{
int currentInt = 1;
//Should be 1
Console.WriteLine(currentInt);
//is 1
TestClass tc = new TestClass(ref currentInt);
//should be 1
Console.WriteLine(currentInt);
//is 1
tc.modInt();
//should be 2
Console.WriteLine(currentInt);
//is 1 :(
}
public class TestClass
{
public int testInt;
public TestClass(ref int testInt)
{
this.testInt = testInt;
}
public void modInt()
{
testInt = 2;
}
}
How do I implement this functionality? I think its not working because I save it in the constructor?
Do I need to do some Box/Unbox jiberish?
static void Main(string[] args)
{
int currentInt = 1;
//Should be 1
Console.WriteLine(currentInt);
//is 1
TestClass tc = new TestClass(ref currentInt);
//should be 1
Console.WriteLine(currentInt);
//is 1
tc.modInt();
//should be 2
Console.WriteLine(currentInt);
//is 1 :(
}
public class TestClass
{
public int testInt;
public TestClass(ref int testInt)
{
this.testInt = testInt;
}
public void modInt()
{
testInt = 2;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上你不能。不直接。 “按引用传递”别名仅在方法本身内有效。
最接近的是拥有一个可变包装器:
然后:
您可能会在 "ref 返回和 ref 局部变量" 有趣。
You can't, basically. Not directly. The "pass by reference" aliasing is only valid within the method itself.
The closest you could come is have a mutable wrapper:
Then:
You may find Eric Lippert's recent blog post on "ref returns and ref locals" interesting.
你可以很接近,但这实际上只是乔恩的变相答案:
You can come close, but it is really just Jon's answer in disguise: