我在以下方法中有几个问题。专家能帮助我理解结构和为什么会出现错误吗?“类型”字符串“必须是不可空和通用方法”
我有这样的方法,将获得一个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,它不工作以及...
任何帮助,真的很受欢迎!谢谢!
'where T:struct' string is not a struct – Jonesopolis
'string'不是'struct'。看起来这种方法只能用于枚举。对于你想要做的只是'string text =(string)element.Attribute(“search”)?? “默认值”;' – juharr
你应该阅读一些关于约束的内容,例如这里[对类型参数的约束(C#编程指南)](https://msdn.microsoft.com/zh-cn/library/d5x73970.aspx) – thehennyy