![](/img/trans.png)
[英]The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'
[英]The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or 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;
}
但是當我嘗試將其與string
一起使用時,仍然出現以下錯誤:類型“ string”必須為不可為空的值類型,才能在通用類型或方法中將其用作參數“ T”
有人可以告訴我為什么嗎? 謝謝
您已將T
參數限制為
where T : struct
struct
限制意味着只能為T
提供值類型。 string
(更確切地說是System.String
)是一個類,一種引用類型。
取消該限制並不是一件容易的事,因為您將T
用作T?
即可空T
Nullable<T>
依次僅接受值類型。
您必須對您是否允許引用類型決定-如果你想限制T
引用類型,使用class
約束,而不是struct
(並刪除?
從T?
,引用類型總是為空的自己) 。 如果要同時允許值和引用類型,則不能創建T
的可空版本。 如果您需要所有這些,請擴展對情況的描述,以便我們幫助您找到更好的解決方案。
因為您將T限制為值類型- where T : struct, IComparable
,而string是引用類型。
字符串不是值類型,它是不可變的引用類型,因此它違反了T必須為struct
的通用約束。
請參閱string
類型文檔,以獲取有關string
更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.