C# 返回可为空的字符串类型
所以我有类似的东西C# 返回可为空的字符串类型,c#,string,nullable,C#,String,Nullable,所以我有类似的东西 public string? SessionValue(string key) { if (HttpContext.Current.Session[key].ToString() == null || HttpContext.Current.Session[key].ToString() == "") return null; return HttpContext.Current.Session[key].ToString(); } 它不能
public string? SessionValue(string key)
{
if (HttpContext.Current.Session[key].ToString() == null || HttpContext.Current.Session[key].ToString() == "")
return null;
return HttpContext.Current.Session[key].ToString();
}
它不能编译
如何返回可为空的字符串类型?字符串已经是可为空的类型。Nullable只能用于ValueType。字符串是引用类型
只要扔掉“?”你就可以走了 由于字符串是引用类型,您可以将其赋值为null,因此不需要使其可为null。字符串已经是可为null的类型。你不需要“?”这个词 错误18类型“string”必须是 不可为空的值类型,以便 将其用作泛型中的参数“T” 类型或方法“System.Nullable”
string
本身就可以为null。正如其他人所说,string
不需要?
(这是nullable
的快捷方式),因为所有引用类型(class
es)都可以为null。它仅适用于值类型(struct
s)
除此之外,在检查会话值是否为null
(或者您可以获得NullReferenceException
)之前,不应对会话值调用ToString()。此外,您不必检查ToString()
的null
结果,因为它永远不会返回null
(如果正确实现)。如果会话值是空的字符串(“
”),是否确实要返回null
这相当于你想写的内容:
public string SessionValue(string key)
{
if (HttpContext.Current.Session[key] == null)
return null;
string result = HttpContext.Current.Session[key].ToString();
return (result == "") ? null : result;
}
尽管我会这样写(如果会话值包含空的字符串,则返回空的):
“因为所有引用类型(类)都已可为空。”--><代码>公共类向量{public static vector func(){return null;}}
导致错误。接口似乎可以为空always@Assimilater我刚试过你的密码。它对我来说编译并运行得很好vector
是一个类,因此func()
肯定可以返回null
。我的错。我在结构和类之间跳跃,它们是不同的
public string SessionValue(string key)
{
object value = HttpContext.Current.Session[key];
return (value == null) ? null : value.ToString();
}