首页 > 解决方案 > 如何检查对象的多个属性是否有价值

问题描述

我有一个有 n 个属性的类,我需要知道是否有超过 1 个属性有值,它会是假的,我写了一个类似CheckValue的方法

 public class ClassExample
    {
        public ClassExample(string value1, string value2, string value3)
        {
            Value1 = value1;
            Value2 = value2;
            Value3 = value3;
            if (CheckValue()) throw new Exception("Not allow set value for both Value1, Value2, Value3");
        }
        public string Value1 { get;  }
        public string Value2 { get;  }
        public string Value3 { get; }

        public bool CheckValue()
        {
            if ((Value1 != null ? 1 : 0) +
                (Value2 != null ? 1 : 0) +
                (Value3 != null ? 1 : 0) > 1)
            {
                return true;
            }

            return false;
        }
    }

有没有更好的方法来编写 CheckValue 方法?

标签: c#design-patterns

解决方案


您可以执行以下操作。例如,假设您所关注的属性以模式 Value_ 命名。您可以根据需要更改搜索过滤器。

public bool CheckValue()
{
       return this.GetType().GetProperties()
               .Where(property=> property.Name.StartsWith("Value"))
               .Count(property=>property.GetValue(this,null)!=null)>=1;

}

如果您不想过滤属性,可以执行以下操作。

 return `this.GetType().GetProperties().Count(property=>property.GetValue(this,null)!=null)>=1;

您可能还必须识别值类型的预期/默认值并添加相同的检查,因为上面的查询仅检查空值。但请注意使用反射的性能影响。


推荐阅读