Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 返回可为空的字符串类型_C#_String_Nullable - Fatal编程技术网

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();
}