返回可以为空的字符串类型

sar*_*ake 15 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();
}
Run Code Online (Sandbox Code Playgroud)

哪个不编译.

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

And*_*ite 36

String已经是可以为空的类型.Nullable只能用于ValueTypes.String是引用类型.

只是摆脱"?" 你应该好好去!


Luc*_*cas 7

正如其他人所说,string不需要?(这是 的快捷方式Nullable<string>),因为所有引用类型(classes)都已经可以为空。它仅适用于值类型struct

除此之外,ToString()在检查会话值是否存在null(或者可以获得一个NullReferenceException)之前,您不应该调用会话值。另外,您不必检查ToString()for的结果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;
}
Run Code Online (Sandbox Code Playgroud)

尽管我会这样写(string如果会话值包含该内容,则返回空):

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