2010-09-08 40 views
-1
public class MyClass<T> 
{ 
     public T this[int index] 
     { 
      get 
      { 
       ... 
      } 
      set 
      { 
       ... 
      } 
     } 

     public void MyMethod<T>() 
     { 
      int middleIndex = ...;    
      T value = this[middleIndex ];  
      ...    
     }   
} 

由於MyMethod()中的語句,代碼無法編譯。是否有另一種調用索引器的方式?從相同(通用)類中調用索引器

編輯:修飾的MyMethod()

EDIT2:編譯錯誤

Error 6 Cannot implicitly convert type 'T [C:\MyClass.cs]' to 'T [C:\MyClass.cs]' 

感謝。

+0

'MyMethod'中定義的'index'在哪裏? – Larsenal 2010-09-08 18:48:11

+1

如果我用「public void MyMethod(int index)」替換MyMethod,那麼這個例子編譯得很好。 – 2010-09-08 18:49:00

+0

你發佈的代碼看起來很好。你能發佈更多'MyMethod'嗎? – Larsenal 2010-09-08 18:49:44

回答

3

正常工作:

public class MyClass<T> 
{ 
    public T this[int index] 
    { 
     get 
     { 
      return default(T); 
     } 
     set 
     { 
     } 
    } 

    public void MyMethod(int index) 
    {     
     T value = this[index];  
    }   
} 

誠然,我已經向大家介紹了index參數爲MyMethod,但我假設你希望得到來自地方指數...如果這不是你的意思是,請澄清。

0

你沒有傳入索引值到方法MyMethod - 你可以發佈多一點的代碼嗎?它看起來像缺少一些東西...

1

調用索引器是好的,但它不知道你想要哪個索引。如果你使索引MyMethod的參數,它會正常工作。

如果你想獲得當前的索引或者其他東西,那麼你需要存儲一個私有變量,將它連接到索引器並訪問它。

你編輯的代碼編譯正常...

public class MyClass<T> 
{ 
     public T this[int index] 
     { 
      get 
      { 
       ... 
      } 
      set 
      { 
       ... 
      } 
     } 

     public void MyMethod() 
     { 
      int middleIndex = ...;    
      T value = this[middleIndex ];  
      ...    
     }   
} 
2

這對我工作得很好:

public class MyClass<T> 
{ 
    List<T> _items = new List<T>(); 

    public T this[int index] 
    { 
     get 
     { 
      return _items[index]; 
     } 
    } 

    public void MyMethod() 
    { 
     T value = this[2]; 
    } 
} 
0

你的問題的代碼是在這裏:

public void MyMethod<T>() 

MyClass<T>類已經有泛型類型參數T,所以上的通用是不必要的

+0

這是因爲你聲明瞭一個新的T而與外部T無關。 – sisve 2010-09-09 14:40:23

相關問題