2011-07-05 1 views
7

Comment implémenter cette fonctionnalité? Je pense que cela ne fonctionne pas parce que je l'enregistre dans le constructeur? Ai-je besoin de faire du Box/Unbox jiberish?passez la valeur par référence dans le constructeur, sauvegardez-la, puis modifiez-la plus tard, comment?

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

    } 

Répondre

12

Vous ne pouvez pas, fondamentalement. Pas directement. L'aliasing "passer par référence" n'est valide que dans la méthode elle-même.

Le plus proche que vous pourriez venir est d'avoir un emballage mutable:

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

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

Puis:

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

Vous pouvez trouver de blog récent Eric Lippert sur "ref returns and ref locals" intéressant.

+0

Merci, c'était vraiment utile. –

0

Vous pouvez venir à proximité, mais il est vraiment juste réponse Jon déguisé:

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 
Questions connexes