返回可空字符串类型

18

所以我有一个类似这样的东西

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

编译不通过。

我该如何返回可空字符串类型?

5个回答

42

字符串已经是一个可空类型。 可空类型只能用于值类型。 字符串是引用类型。

只需去掉“?”即可!


7
就像其他人所说的那样,string不需要问号(?)(它是Nullable的快捷方式),因为所有引用类型(如class)已经是可空类型。它只适用于值类型(如struct)。
除此之外,在检查会话值是否为null之前,您不应该调用ToString()(否则可能会出现NullReferenceException)。而且,您不应该检查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;
}

尽管我会这样写(如果会话值包含空的 string,则返回空字符串):

public string SessionValue(string key)
{
    object value = HttpContext.Current.Session[key];
    return (value == null) ? null : value.ToString();
}

似乎并非如此。public class vector { public static vector func() { return null; } } 会导致错误,因为所有引用类型(类)并非都可为空。 - Assimilater
接口似乎总是可为空的。 - Assimilater
1
@Assimilater 我刚试了一下你的代码。它在我的电脑上编译和运行都很好。vector是一个类,所以func()肯定可以返回null - Lucas
我的错。我在结构体和类之间反复切换,它们是不同的。 :) - Assimilater

0

字符串是一个引用类型,因此您可以将null分配给它,您不需要使其可为空。


0

字符串已经是可为空的类型。你不需要“?”。

错误18:“string”类型必须是非空值类型,才能在泛型类型或方法“System.Nullable”中用作参数“T”。


0

string 本身就已经是可空的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接