2016-08-05 43 views
-3

我在以下方法中有幾個問題。專家能幫助我理解結構和爲什麼會出現錯誤嗎?「類型」字符串「必須是不可空和通用方法」

我有這樣的方法,將獲得一個XML元素,搜索在name參數指定的屬性,並且情況下可以在XML沒有找到,則返回默認值:

protected static T GetValue<T>(XElement group, string name, T default)  where T : struct 
{ 
      //Removed some code for better view 
      XAttribute setting = group.Attribute(name); 
      return setting == null ? default: (T)Enum.Parse(typeof(T), setting.Value); 
} 

我的問題是關於此方法中使用的泛型類型。當我嘗試在一個字符串變量使用這種方法,我得到以下錯誤:

string test = GetValue(element, "search", "default value"); The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'GetValue(XElement, string, T)'

什麼T是這種方法,是我收到該錯誤的問題? T:struct是什麼意思?我試圖使用這個作爲GetValue,它不工作以及...

任何幫助,真的很受歡迎!謝謝!

+2

'where T:struct' string is not a struct – Jonesopolis

+2

'string'不是'struct'。看起來這種方法只能用於枚舉。對於你想要做的只是'string text =(string)element.Attribute(「search」)?? 「默認值」;' – juharr

+0

你應該閱讀一些關於約束的內容,例如這裏[對類型參數的約束(C#編程指南)](https://msdn.microsoft.com/zh-cn/library/d5x73970.aspx) – thehennyy

回答

2

where T : struct是對通用類型T的約束,這意味着它必須是struct。由於string不是struct,而您傳遞的是string,即"default value",您將收到錯誤消息。

1

string不是struct每個通用約束where T : struct。看起來這種方法只能用於基於使用Enum.Parse的枚舉。你想要的東西只是做

string text = (string)element.Attribute("search") ?? "default value"; 

你可以做最值的類型類似的東西以及

int value = (int?)element.Attribute("intAttribute") ?? -1; 

退房的XAttribute文檔,哪些類型可以顯式轉換。

但是,這不適用於轉換爲枚舉,這可能是爲什麼寫這個方法。

相關問題