C# nullable string error

private string? typeOfContract
{
get { return (string?)ViewState["typeOfContract"]; }
set { ViewState["typeOfContract"] = value; }
}

Later in the code I use it like this:

typeOfContract = Request.QueryString["type"];

I am getting the following error at the declaration of typeOfContract line stating:

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>'

Any ideas? Basically, I want to make sure that "type" exists in the QueryString before performing an action.

138643 次浏览

System.String 是一个引用类型,并且已经“可为空”。

Nullable < T > 和? 后缀用于值类型,如 Int32、 Double、 DateTime 等。

你把事情搞复杂了。string已经可以为空。你不需要使它 更多为空。取出属性类型上的 ?

字符串不能是 Nullable 的参数,因为字符串不是值类型。字符串是引用类型。

string s = null;

是一个非常有效的语句,没有必要使其为空。

private string typeOfContract
{
get { return ViewState["typeOfContract"] as string; }
set { ViewState["typeOfContract"] = value; }
}

应该工作,因为 作为关键字。

String 是一个引用类型,所以在这里不需要(也不能)使用 Nullable<T>。只需将 typeOfContractasstring 声明为字符串,并在从查询字符串获取它之后简单地检查 null。如果希望处理与 null 相同的空字符串值,可以使用 String.IsNullOrEmpty。

对于 nullable,除字符串外,对所有 C # 原语使用 ?

下面的页面列出了 C # 原语的清单: Http://msdn.microsoft.com/en-us/library/aa711900(v=vs.71).aspx