2011-07-05 10 views
7

この機能を実装するにはどうすればよいですか?私はそれがコンストラクタに保存するので、動作しないと思いますか? 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; 
     } 

    } 

答えて

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

あなたが面白い"ref returns and ref locals"にエリックリペットの最近のブログ記事を見つけることができ

あなたが来ることができる最も近い可変ラッパーを持っています。

+0

おかげで、それは本当に役に立ちました。 –

0

は、あなたが近くに来ることができますが、それは本当に変装してちょうどJonの答えです:

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 
関連する問題