2011-07-05 11 views
7

¿Cómo implemento esta funcionalidad? Creo que no funciona porque lo guardo en el constructor. ¿Debo hacer algo de box/unbox jiberish?pase el valor por referencia en el constructor, guárdelo, luego modifíquelo más tarde, ¿cómo?

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; 
     } 

    } 

Respuesta

12

No se puede, básicamente. No directamente. El alias de "paso por referencia" solo es válido dentro del método mismo.

Lo más cerca que podría llegar es tener un envoltorio mutable:

public class Wrapper<T> 
{ 
    public T Value { get; set; } 

    public Wrapper(T value) 
    { 
     Value = value; 
    } 
} 

continuación:

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; 
    } 
} 

Usted puede encontrar reciente post de Eric Lippert en "ref returns and ref locals" interesante.

+0

Gracias, eso fue muy útil. –

0

Usted puede acercarse, pero en realidad es sólo la respuesta de Jon en el encubrimiento:

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 
Cuestiones relacionadas