2011-07-05 29 views
7

Làm cách nào để triển khai chức năng này? Tôi nghĩ rằng nó không hoạt động bởi vì tôi lưu nó trong constructor? Tôi có cần phải làm một số Box/Unbox jiberish?giá trị truyền theo tham chiếu trong hàm tạo, lưu nó, sau đó sửa đổi nó sau, làm thế nào?

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

    } 

Trả lời

12

Bạn không thể, về cơ bản. Không trực tiếp. Bí danh "truyền theo tham chiếu" chỉ hợp lệ trong chính phương thức đó.

Gần nhất bạn có thể đến là có một wrapper có thể thay đổi:

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

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

Sau đó:

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

Bạn có thể tìm thấy bài viết trên blog gần đây Eric Lippert về "ref returns and ref locals" thú vị.

+0

Cảm ơn, đó là thực sự hữu ích. –

0

Bạn có thể đến gần, nhưng nó thực sự chỉ là câu trả lời của Jon trong ngụy trang:

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 
Các vấn đề liên quan