(使用 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有什么烦恼呢?
如果您导航到
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
进行额外的空检查