如何实现此功能?我认为它不起作用,因为我将它保存在构造函数中? 我需要做一些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;
}
}
答案 0 :(得分:12)
你最接近的是有一个可变的包装器:
public class Wrapper<T>
{
public T Value { get; set; }
public Wrapper(T value)
{
Value = value;
}
}
然后:
Wrapper<int> wrapper = new Wrapper<int>(1);
...
TestClass tc = new TestClass(wrapper);
Console.WriteLine(wrapper.Value); // 1
tc.ModifyWrapper();
Console.WriteLine(wrapper.Value); // 2
...
class TestClass
{
private readonly Wrapper<int> wrapper;
public TestClass(Wrapper<int> wrapper)
{
this.wrapper = wrapper;
}
public void ModifyWrapper()
{
wrapper.Value = 2;
}
}
您可能会发现Eric Lippert最近发表的关于"ref returns and ref locals"的博客文章很有趣。
答案 1 :(得分:0)
你可以近距离接触,但这只是乔恩的伪装回答:
Sub Main()
Dim currentInt = 1
'Should be 1
Console.WriteLine(currentInt)
'is 1
Dim tc = New Action(Sub()currentInt+=1)
'should be 1
Console.WriteLine(currentInt)
'is 1
tc.Invoke()
'should be 2
Console.WriteLine(currentInt)
'is 2 :)
End Sub