【问题标题】:C# Dynamically determine class properties based on configuration for comparisonC#根据配置动态确定类属性进行比较
【发布时间】:2020-10-15 08:12:57
【问题描述】:

我定义了一个配置,用于对下面模型中的每个属性进行重复检查

public class ConfigurationModel
{
    public GroupValue Value1 { get; set; }
    public GroupValue Value2 { get; set; }
    public GroupValue Value3 { get; set; }
    public GroupValue Value4 { get; set; }
    public GroupValue Value5 { get; set; }
}
public class GroupValue
{
    public bool duplicateCheck { get; set; }
}

我有一个真正的类,它具有定义的所有属性,如 Value1、Value2 等,我们将其称为 OrderModel

public class OrderModel
{
    public string Value1 { get; set; }
    public string Value2 { get; set; }
    public string Value3 { get; set; }
    public string Value4 { get; set; }
    public string Value5 { get; set; }
}

现在我只想包含那些在配置中将相应标志设置为 true 的属性以进行重复检查。示例

bool CheckDuplicate(OrderModel newOrder)
{
OrderModel existingOrder = //GetfromDB;
//Compare only those properties in newOrder and existingOrder which have duplicate check set to true in ConfigurationModel
}

使用反射通过字符串名称获取属性然后比较是我的想法,但想检查最好的方法,同时牢记性能。任何帮助将不胜感激。

谢谢, AK

【问题讨论】:

    标签: c# reflection dynamic-attributes


    【解决方案1】:

    当我理解正确时,编译时不知道属性? 在这种情况下,我认为最好的方法是使用反射。 (通过使用 nameof() 函数从反射对象中获取属性,您可以获得一种类型安全性,而不是使用硬编码字符串)。

    另一方面,如果您知道编译时设置的完整属性,则可以根据 ConfigurationModel 中的设置为属性创建受控重复检查。

    编辑: 简单地尝试一种对数据库的命中测试:

    bool CheckDuplicate(OrderModel newOrder)
    {
      OrderModel existingOrder = //GetfromDB WHERE dbOrder.Value1 == newOrder.Value1 AND dbOrder.Value2 == newOrder.Value2 AND_SO_ON;
      if(existingOrder/*.FirstOrDefault() -> if IEnumerble is returned from DB*/ == null) return false;
      return true;
    }
    

    【讨论】:

    • 我在编译时就知道完整的属性。如此控制如果检查如 if(value1 duplicatecheck == true),然后比较 value1 属性,类似地重复 5 次,然后对所有 5 个值执行最终 &&? ——
    • @KeenUser,是的,像这样或者更好的方法是对数据库执行存在查询(使用过滤器对数据库的所有需要​​的 newOrder 属性进行查询)。如果没有返回项目,则 newOrder 是唯一的,如果没有,您需要处理您的复制过程
    猜你喜欢
    • 2015-02-28
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多