gpt4 book ai didi

c# - 在 C# 中,比较字符串与 null 和 ""返回 true 的最佳方法是什么

转载 作者:可可西里 更新时间:2023-11-01 08:50:35 26 4
gpt4 key购买 nike

我有以下代码(因为我正在尝试检测字段的更改)

 if (person.State != source.State)
{
//update my data . .
}

问题是我遇到了 person.State 为 NULL 且 source.State 为 ""并因此返回 true 的情况。

如果一个为 null 而另一个为空字符串,我想将它们视为相等并且不更新我的数据。最干净的方法是什么?我是否需要创建自己的 Comparer 对象,因为这似乎是一个普遍的问题

最佳答案

如果你真的需要,你可以这样做:

if ((person.State ?? string.Empty) != (source.State ?? string.Empty))
{
// ...
}

但是,根据您的需要,更好的解决方案可能是修改您的 person.State 属性以永不返回空值。

public class Person
{
string _state = string.Empty;
public string State
{
get { return _state; }
set { _state = value ?? string.Empty; }
}
}

关于c# - 在 C# 中,比较字符串与 null 和 ""返回 true 的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11995619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com