2011-08-22 43 views
3

我已經創建像無法應用索引,以類型的表達式「T」

public void BindRecordSet<T>(IEnumerable<T> coll1, string propertyName) 
      where T : class 

,並在我的課「T」我已經寫索引泛型方法

public object this[string propertyName] 
    { 
     get 
     { 
      Type t = typeof(SecUserFTSResult); 
      PropertyInfo pi = t.GetProperty(propertyName); 
      return pi.GetValue(this, null); 
     } 
     set 
     { 
      Type t = typeof(SecUserFTSResult); 
      PropertyInfo pi = t.GetProperty(propertyName); 
      pi.SetValue(this, value, null); 
     } 
    } 

現在在我的方法,當我寫的代碼像

var result = ((T[])(coll1.Result))[0];

string result= secFTSResult[propertyName];

我收到錯誤 無法適用索引類型爲「T」

請幫 感謝

+0

嗨BoltClock,BindRecordSet 方法泛型類型的方法,在這裏T是BindRecordSet 其中學生是一類 –

回答

6

除非你使用一個通用的限制,其聲明索引器的接口的表情,然後確實 - 這不會存在abitraryT。考慮加入:

public interface IHasBasicIndexer { object this[string propertyName] {get;set;} } 

和:

public void BindRecordSet<T>(IEnumerable<T> coll1, string propertyName) 
     where T : class, IHasBasicIndexer 

和:

public class MyClass : IHasBasicIndexer { ... } 

(隨意命名IHasBasicIndexer的東西更明智的)

或在4.0簡單的替代方法(但有點hacky IMO):

dynamic secFTSResult = ((T[])(coll1.Result))[0];  
string result= secFTSResult[propertyName]; 

(這將解決它每一次在T運行時)

+1

我寧願'接口IIndexable {這[T指數] {得到;組; }}'以匹配BCL風格。我很驚訝它不存在.... –

+0

@Simon所描述的接口採用'string'並返回'object' - 這裏的T是哪裏? –

+0

@MSingh - 我在答案中遺漏了一個'object';看更新(到接口定義) –

相關問題