c# - 如何检查对象的多个属性是否有价值
问题描述
我有一个有 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 方法?
解决方案
您可以执行以下操作。例如,假设您所关注的属性以模式 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;
您可能还必须识别值类型的预期/默认值并添加相同的检查,因为上面的查询仅检查空值。但请注意使用反射的性能影响。
推荐阅读
- python - 不平衡面板数据:如何使用时间序列拆分交叉验证?
- linux - Linux 一个带有管道操作的长 shell 命令
- node.js - 如何从节点进行共享点宁静调用
- c# - 在 SOLR DB 中,当我执行查询时我有数据,但是当我尝试在代码中执行此操作时,我有一个包含空数据的数组
- google-tag-manager - 自定义模板 callInWindow
- postgresql - PostgreSQL:比较同一列但不同系列(行)中的字符串
- maven - 如何在 Maven 依赖项的另一个 war 文件中添加 jar?
- javascript - 选择 5 张时排队要立即上传的图像
- c# - 如何区分具有相同 id 的两个 WebElement?
- exchangewebservices - 日历 - 对约会应用搜索过滤器(主题)