[英]The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method
I followed the suggestion around this web site to made the following method: 我按照该网站上的建议进行了以下操作:
public static T? GetElementValue<T>(this XElement xElement, string s)
where T : struct, IComparable
{
var result = new Nullable<T>();
try
{
if (string.IsNullOrEmpty(s) || s.Trim().Length > 0 || xElement.IsEmpty)
return result;
var element = xElement.Element(s);
if (element == null || element.IsEmpty)
return result;
var conv = TypeDescriptor.GetConverter(typeof(T));
result = (T)conv.ConvertFrom(element.Value);
}
catch (Exception ex)
{
ex.Message.WriteAsError();
}
return result;
}
but when I try to use it with a string
I still get the following error: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 但是当我尝试将其与
string
一起使用时,仍然出现以下错误:类型“ string”必须为不可为空的值类型,才能在通用类型或方法中将其用作参数“ T”
Someone can tell me why? 有人可以告诉我为什么吗? Thx
谢谢
You have restricted your T
parameter by 您已将
T
参数限制为
where T : struct
The struct
restriction means that only value types can be supplied for T
. struct
限制意味着只能为T
提供值类型。 string
(more precisely, System.String
) however, is a class, a reference type. string
(更确切地说是System.String
)是一个类,一种引用类型。
Removing that restriction will not be quite trivial, as you use T
as T?
取消该限制并不是一件容易的事,因为您将
T
用作T?
, ie a nullable T
. 即可空
T
Nullable<T>
in turn only accepts value types. Nullable<T>
依次仅接受值类型。
You will have to decide on whether you want to allow reference types - if you want to restrict T
to reference types, use the class
constraint instead of struct
(and drop the ?
from T?
, as reference types are always nullable on their own). 您必须对您是否允许引用类型决定-如果你想限制
T
引用类型,使用class
约束,而不是struct
(并删除?
从T?
,引用类型总是为空的自己) 。 If you want to allow both value and reference types, you cannot make a nullable version of T
. 如果要同时允许值和引用类型,则不能创建
T
的可空版本。 If you need all of these, please extend your description of the circumstances so we can help you find a better solution. 如果您需要所有这些,请扩展对情况的描述,以便我们帮助您找到更好的解决方案。
因为您将T限制为值类型- where T : struct, IComparable
,而string是引用类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.