2010-06-20 73 views
1

我想建立一個泛型類,我可以用它來實現C#中的參數化屬性。基本代碼我想是這樣的:通過泛型實現的C#參數化屬性類?

public class ParameterizedProperty<typeReturn, typeIndexer> { 
    private typeReturn oReturn = default(typeReturn); 

    public typeReturn this[typeIndexer oIndexer] { 
     get { return oReturn[oIndexer]; } 
     set { oReturn[oIndexer] = value; } 
    } 
} 

但由於typeReturn未知/不受限制的編譯器plotzing在oReturn[oIndexer]線。

那麼我如何得到這個工作?我的第一個(好的,第二個)想法是使用Reflection來有條件地找到索引器(並且如果找不到索引器會產生錯誤),或者對類定義使用修飾符。但是如果我使用修飾詞,I???會是什麼?

感謝您對此問題的任何解決方案!

注意:如何通過反射正確找到索引器(假設)在這裏找到:http://www.dotnet247.com/247reference/msgs/3/16665.aspx(請參閱最後一條消息)。

編輯:正如馬修在下面指出的......我在原始描述中遇到了一些錯誤/錯誤......我自己的錯,真的......原本在睡覺前寫這篇文章!我想要的代碼看起來更像是這樣的:

public class ParameterizedProperty<typeReturn, typeIndexer> { 
    private typeReturn[] oReturn; 

    public ParameterizedProperty(typeReturn[] oSource) { 
     oReturn = oSource; 
    } 

    public typeReturn this[typeIndexer oIndexer] { 
     get { return oReturn[oIndexer]; } 
     set { oReturn[oIndexer] = value; } 
    } 
} 

...你會打賭什麼作品!?

呃,不完全!仍抱怨typeIndexer(想要一個「int-able」類型),但更多betterer!我還在一個構造函數中添加了一個構造函數來解決這個問題:「我實際上無法設置任何返回值」問題=)

但是,即使這看起來不正確(數組總是被INTs索引,對吧?無需typeIndexer)...

+1

您是否意識到對象的索引器會返回相同類型的實例?這是否意味着樹/圖? – 2010-06-20 14:27:42

+0

不確定我關注Matthew ...如果底層的oReturn是一個bool [],那麼......現在看到它=)T'was是一個錯誤/ bug ...編輯3中的原始問題.. .2 ... – Campbeln 2010-06-21 13:51:29

回答

3

你想沿着這些路線的東西,我將不得不在再次看wurk明天=):

public class ParameterizedProperty<typeReturn, typeIndexer> { 
    private Dictionary<typeIndexer, typeReturn> oReturn = new Dictionary<typeIndexer, typeReturn>(); 

    public typeReturn this[typeIndexer oIndexer] { 
     get { return oReturn[oIndexer]; } 
     set { oReturn[oIndexer] = value; } 
    } 
} 
+0

這確實適用於我的目的,但使用字典來實現字符串[]或bool []會做的事情似乎有點重量級(不必介意討厭的索引器問題;) I猜一個字典的方法會得到我的投票...但至少有幾天我會堅持/實驗=) – Campbeln 2010-06-21 13:41:02

1

既然你顯然不關心具體的安裝業務邏輯到這個索引屬性的getter或setter(就像你可以用C#中的默認索引器或VB.NET中的任何屬性一樣),你需要一個內部st爲了實現這一目標,我們需要一個機制。

public class ParameterizedProperty<TReturn, TIndexer> 
{ 
    private Dictionary<TIndexer, TReturn> storage = new Dictionary<TIndexer, TReturn>(); 

    public TReturn this[TIndexer index] 
    { 
     get 
     { 
      TReturn output; 

      storage.TryGetValue(index, out output); 

      return output; 
     } 
     set { storage[index] = value; } 
    } 
} 

但是這一切確實是爲您提供類似於Dictionary一個結構,但是當指數不存在不拋出異常。

+0

我喜歡使用TryGetValue(我需要查看它,但我會如果get失敗,猜測「默認(TReturn)」是否放在輸出中?)。 是的...沒有必要爲這些索引器/屬性附加add'l功能(總是可以重載/實現一個鉤子,我想),我只是想... public string [] IDs { get {return ga_sIDs; } } ...不將ga_sID暴露給調用者(也不是所有的屬性/方法)。 – Campbeln 2010-06-21 13:46:06

+1

@CampbeIn:是的,如果檢索失敗,'default(TReturn)'是'out'變量的內容。 – 2010-06-21 14:21:33

+0

@CampbeIn:另外,如果你想要一個任意的索引方案,一個'Dictionary'是獲得你要找的東西的唯一方法。數組將無法工作。 'Dictionary'不是一個特別重量級的對象。 – 2010-06-21 14:24:36