2009-08-17 80 views
0

如何捕獲變量?
或者,我可以存儲對象引用的引用嗎?如何捕獲變量(C#)

通常情況下,一種方法可以使用ref關鍵字來改變它之外的變量。

void Foo(ref int x) 
{ 
    x = 5; 
} 

void Bar() 
{ 
    int m = 0; 
    Foo(ref m); 
} 

這是清楚而直截了當的。

現在讓我們考慮一個類來實現同樣的事情:

class Job 
{ 
    // ref int _VarOutsideOfClass; // ????? 

    public void Execute() 
    { 
     // _VarOutsideOfClass = 5; // ????? 
    } 
} 

void Bar() 
{ 
    int m = 0; 
    var job = new Job() 
    { 
     _VarOutsideOfClass = ref m // How ? 
    }; 
    job.Execute(); 
} 

如何正確地寫呢?


點評:我不能使它與ref參數的方法,因爲通常Execute()會在不同的線程有點遲叫,當它在隊列中出現。

目前,我做了充足的lambda表達式的原型:

class Job 
{ 
    public Func<int> InParameter; 
    public Action<int> OnResult; 

    public void Execute() 
    { 
     int x = InParameter(); 
     OnResult(5); 
    } 
} 

void Bar() 
{ 
    int m = 0; 
    var job = new Job() 
    { 
     InParameter =() => m, 
     OnResult = (res) => m = res 
    }; 
    job.Execute(); 
} 

...但也許有一個更好的主意。

+0

您的解決方案對我來說似乎很不錯... – 2009-08-17 13:38:58

回答

1

使用磁盤陣列和1元

class Job{ 
int[] _VarOutsideOfClass = new int[1]; 

你也可以使用包裝 「INT?」 - 原諒他們可以空,但請記住,它總是通過參考。

+0

不,不是。可空是一個結構 – 2009-08-17 14:52:11

+0

是的,原諒空號!但陣列仍然是很好的參考持有者。 – Dewfy 2009-08-17 15:29:38

0

這裏有一個猜測(我還沒有嘗試/測試吧):

class Job 
{ 
    Action<int> m_delegate; 

    public Job(ref int x) 
    { 
    m_delegate = delegate(int newValue) 
    { 
     x = newValue; 
    }; 
    } 

    public void Execute() 
    { 
    //set the passed-in varaible to 5, via the anonymous delegate 
    m_delegate(5); 
    } 
} 

如果上述方法無效,那麼說這個招聘構造函數採用委託作爲其參數,在Bar類中構造委託(並傳遞委託,而不是傳遞ref參數)。

+0

錯誤:無法在匿名方法,lambda表達式或查詢表達式中使用ref或out參數'x' – 2009-08-17 13:55:47

+0

是的,不起作用。 – 2009-08-17 13:58:08