2016-08-05 45 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文档,哪些类型可以显式转换。

但是,这不适用于转换为枚举,这可能是为什么写这个方法。

相关问题