如何避免引用可能为空的引用?

问题描述 投票:0回答:1

(使用 ASP.NET Core 7 和 VS2022)

我有一个实用函数,是从旧的 .NET 项目中引入的:

原版是这样的:

        public static string WriteString(object str)
        {
            if (str == null)
                return "";
            else
                return str.ToString().Trim();
        }

我把它转换成这样:

        public static string WriteString(object str)
        {
            object s = str ?? "";
            return s.ToString().Trim();
        }

但我仍然收到取消引用可能为空引用的警告。我错过了什么吗?我的变量 s 不可能为 null,因为我使用的是 null 合并运算符。那么VS有什么烦恼呢?

visual-studio asp.net-core
1个回答
0
投票

如果您导航到

Object
类定义,您将看到
.ToString()

的签名
    //
    // Summary:
    //     Returns a string that represents the current object.
    //
    // Returns:
    //     A string that represents the current object.
    public virtual string? ToString();

string?
导致
str.ToString()
被评估为
string?
并且
.Trim()
只能对不可空的
string
进行操作。从技术上讲,您永远不会收到错误,但您可能会对
str.ToString() != null

进行额外的空检查
© www.soinside.com 2019 - 2024. All rights reserved.