pass value by reference in constructor, save it, then modify it later, how to?
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
{
开发者_C百科 public int testInt;
public TestClass(ref int testInt)
{
this.testInt = testInt;
}
public void modInt()
{
testInt = 2;
}
}
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:
public class Wrapper<T>
{
public T Value { get; set; }
public Wrapper(T value)
{
Value = value;
}
}
Then:
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;
}
}
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:
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
精彩评论