2015-09-01 73 views
0

我想使用WeakReference並希望將通用類型傳遞給它。使用通用參數並將其存儲在弱引用中

public class SomeDataSource : UICollectionViewDataSource 
{ 
    private WeakReference<T> weakController; 

    public SomeDataSource (T controller) 
    { 
     this.weakController = new WeakReference<T>(controller); 
    } 
} 

當我想訪問我的控制器,我必須知道類型。我想過這樣的事情:

if (typeof(SomeViewController) == weakController.GetType()) { 
    SomeViewController controller; 
    if (weakController.TryGetTarget (out controller)) { 
     // do something 
    } 
} 

這可能嗎?目前我收到

無法找到類型或名稱空間名稱'T'。您是否缺少裝配參考?

無處不在我用T。我的研究表明這種

,但我不知道有沒有用這樣的事情。

+0

'T'必須包括在類定義:'公共類SomeDataSource '此後,您可以在SomeDataSource類中的任何函數中使用'typeof(T)' –

+0

如果我在類定義中使用它,我會得到更多的編譯錯誤,因爲我還沒有定義類型。我不太瞭解使用它的影響。 – testing

回答

1

也許你應該只使用WeakReference<object>它可以存儲任何對象引用。

+0

我得到*無法將'SomeViewController'表達式轉換爲在'TryGetTarget()'上輸入'out object'*。我必須在這裏使用類型轉換嗎?在哪一步? – testing

+1

將該變量輸入爲對象,並稍後再進行強制轉換。 – usr

1

我不能在此刻測試,但你可以不喜歡

public class SomeDataSource : UICollectionViewDataSource 
{ 
    private WeakReference<object> weakController; 

    public SomeDataSource (object controller) 
    { 
     this.weakController = new WeakReference<object>(controller); 
    } 
} 

然後

object o; 
SomeViewController controller; 
if (weakController.TryGetTarget(out o)) 
{ 
    controller = o as SomeViewController; 

    // do something 
} 
+0

我做了* usr *提到它。唯一的區別是我在'TryGetTarget()'中定義了* SomeViewController *。它確實有效,但我的應用程序崩潰之前沒有。我必須更深入地瞭解這一點,但也許我需要另一種方式(根本不使用泛型參數和弱引用)。 – testing

+0

這個改變後會發生什麼事? –

+0

它不應該與這個問題有關,但這裏是:* UICollectionView收到一個索引路徑不存在的單元格的佈局屬性*。如果我使用'WeakReference',它不會崩潰,但如果我使用'WeakReference '它確實。 – testing

相關問題