2012-07-29 60 views
5

所以我得到一個有趣的編譯器錯誤!我也會把它粘貼在這裏:「類型(我的類)必須是非空類型,以便在通用方法中用作參數'T'」類型(我班)必須是非可空類型,才能在一個通用的方法作爲參數「T」使用

這對我沒有意義因爲我的方法不是通用的。這裏是我打電話違規代碼:

Item? inputtedItem = SearchProduct(txtProduct.Text); 

同時,這裏是SearchProduct的定義:

 private Item? SearchProduct(string product) 
    { 
     //If this is the first item to be entered into the inventory 
     if (_inventory == null || _inventory._productList.Count == 0) 
     { 
      return null; 
     } 
     //Return the Item's instance if it appears in the inventory. Otherwise return null. 
     return _inventory[product]; 
    } 

我想我會從我的清單類在這裏添加索引的好措施:

 public Item this[string i] 
    { 
     get 
     { 
      Item returnItem; 
      _productList.TryGetValue(i, out returnItem); 
      return returnItem; 
     } 
     set 
     { 
      _productList.Add(i, value); 
     } 
    } 

有誰知道什麼是錯?

謝謝你的幫助。

+0

是'Item'一個'struct'? – dtb 2012-07-29 23:51:14

+0

SearchProduct是接口方法的一個實現嗎?可能有一個通用參數「T」的接口,您輸入了「Item」? – Virtlink 2012-07-29 23:53:19

+0

我覺得TryGetValue是你的通用方法。 _productList的類型究竟是什麼? – 2012-07-29 23:58:34

回答

6

我不認爲你需要Item??。如果Item是一個自定義的類,它會默認爲空。

+0

我認爲你可能已經擊中了頭部。 Item曾經是struct,這就是爲什麼我需要使它爲空。我忘記了默認的類是引用類型,所以它們總是可以爲空的。讓我看看如果改變它的作品!謝謝 – Nick 2012-07-30 00:07:29

相關問題