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

哪个不编译。

如何返回可为空的字符串类型?

4

5 回答 5

41

String 已经是可以为空的类型。Nullable 只能用于 ValueTypes。字符串是引用类型。

只需摆脱“?” 你应该好好去!

于 2009-05-29T22:23:46.877 回答
6

正如其他人所说,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();
}
于 2009-05-29T22:54:09.857 回答
0

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

于 2009-05-29T22:24:41.273 回答
0

String 已经是可以为空的类型。你不需要'?'。

错误 18 类型“字符串”必须是不可为空的值类型,才能将其用作泛型类型或方法“System.Nullable”中的参数“T”

于 2009-05-29T22:26:54.640 回答
0

string本身已经可以为空。

于 2009-05-29T22:28:20.877 回答