检查字符串对象数组中的空值

本文关键字:空值 数组 字符串 对象 检查 | 更新日期: 2023-09-27 18:36:12

我认为这是一个

相当基本的问题,但要么我的大脑还没有醒来,要么我只是很厚!

我有一个类,它有一个属性,上面定义的字符串集合(名称被简化)

public class IdentifierCollection : BaseSubCollection, IIdentifierCollection
{
    public string Id1{ get; set; }
    public string Id2{ get; set; }
    public string Id3{ get; set; }
    // ...      
}

我想在保存之前检查是否有任何属性实际上具有值,所以我目前正在做这样的事情......

if (string.IsNullOrEmpty(primaryObj.Identifiers?.Id2) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id2) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id3) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id4) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id5) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id6) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id7) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id8))
{
}

只是输入这个感觉不对!!一定有更好的方法...

检查字符串对象数组中的空值

我认为

这种属性检查没有任何问题。使用反射或实现一些接口只是为了能够迭代属性对我来说似乎是矫枉过正。虽然我同意这么长的陈述作为条件检查看起来很尴尬。为了使代码更具可读性,我将此检查提取到单独的私有方法中。

if (NoPropIsNullOrEmpty())
{
}
private bool NoPropIsNullOrEmpty()
{
    return !(string.IsNullOrEmpty(primaryObj.Identifiers?.Id2) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id2) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id3) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id4) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id5) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id6) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id7) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id8));
}