c# - 谁能理解/解释这个字符串扩展?

标签 c# string

我们有一个名为“StringExtensions”的文件,它作为一个“类”,可用于我假设的多个数据集/模型。

谁能帮助理解这个 ToSafeString 对字符串的作用?

public static string ToSafeString(this object source)
{
    return source?.ToString() ?? string.Empty;
}

最佳答案

它使用 source? 检查对象是否不为 null。如果它不是null,则调用ToString() 并返回结果。如果是null,则返回string.Empty

它使用 (.?) null conditional(??) null-coalescing运营商。

关于c# - 谁能理解/解释这个字符串扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52060638/

相关文章:

c# - Fluent Nhibernate ManyToMany 集合 - 不保存关联

android - 字符串 xml 写入 "<"

python - 如何使用Python搜索字典值是否包含特定字符串

c# - 元素出现次数最多的列表

c# - 代码约定的条件属性异常

c# - 函数返回的字符串

c - 将字符串从结构传递到字符串数组 - C

python将多行转换为单行

c# - 使用 Fluent Nhibernate Table-Per-Subclass 策略时可以指定身份列吗?

c# - 程序集绑定(bind)重定向 : How and Why?