正如其他人所说,string不需要?(这是 的快捷方式Nullable<string>),因为所有引用类型(classes )都已经可以为空。它仅适用于值类型 ( structs)。
除此之外,您不应该ToString()在检查它是否是之前调用会话值null(或者您可以获得一个NullReferenceException)。此外,您不必检查 for 的结果,ToString()因为null它永远不会返回null(如果正确实施)。null如果会话值为空string( "") ,您确定要返回吗?
这相当于您要写的内容:
public string SessionValue(string key)
{
if (HttpContext.Current.Session[key] == null)
return null;
string result = HttpContext.Current.Session[key].ToString();
return (result == "") ? null : result;
}
虽然我会这样写(string如果这是会话值包含的内容,则返回空):
public string SessionValue(string key)
{
object value = HttpContext.Current.Session[key];
return (value == null) ? null : value.ToString();
}