繁体   English   中英

如果名称与字段名称不同,如何通过反射获取字段值

[英]How can I get field value via reflection if name is different with field name

我有一个 class

 [BsonIgnoreExtraElements]
    public class CustomerModel
    {        
        public string BranchID { get; set; }       
        public string BranchName { get; set; }        
        public string ReceiverID { get; set; }
        public string ReceiverName{ get; set; }       

        }

我正在编写一个过滤器活动,它可以验证在 MongoDB 中配置的具有特定值的任何字段

"Exclude":[{"SourceCol":"Receiver Mode ID","Values":{"Value":["G","8","J"]}}

并将比较逻辑写为

 public static object GetPropValue(object src, string propName)
        {
            return src.GetType().GetProperty(propName).GetValue(src, null);
        }

        public static bool CheckPropertyCompare(CustomerModel customer, Exclude item)
        {
            var propertyValue = GetPropValue(customer, item.SourceCol);
            return item.Values.Value.ToList().Contains(propertyValue);

        }

在这里,来自 MongoDB 的接收器模式 ID实际上是在寻找ReceiverID ,我不知道如何解决这个问题。 我能想到的唯一选择是键值对集合来获取字段名称。 但想知道是否有像属性这样的选项可以简化这个过程。

TIA

我认为你可以用你所说的属性来实现这一点。

您可以创建自定义属性,如下所示:

internal class MongoDBFieldAttribute : Attribute
{
    public string Field{ get; private set; }

    public MongoDBFieldAttribute(string field)
    {
        this.Field= field;
    }
}

然后在您的 class 中:

public class CustomerModel
{        
    ...
    [MongoDBField("ReceiverModeID")]
    public string ReceiverID { get; set; }
}

我认为没有空格可能会更好,这可能是一个问题,也许你可以使用 Trim() 或类似的......或者你可以尝试 [MongoDBField("Receiver Mode ID")],从未尝试过。

然后,您可以创建一个方法,而不是关联属性名称和属性名称,例如:

   private Dictionary<string, string> getRelationPropertyAttribute(Type type)

    {
        var dicRelation = new Dictionary<string, string>();

        var properties = type.GetProperties();
        foreach (var property in properties)
        {
            var attributes = property.GetCustomAttributes(inherit: false);

            var customAttributes = attributes
                .AsEnumerable()
                .Where(a => a.GetType() == typeof(MongoDBFieldAttribute));

            if (customAttributes.Count() <= 0)
                continue;

            foreach (var attribute in customAttributes)
            {
                if (attribute is MongoDBFieldAttribute attr) 
                    dicRelation[attr.Field] = property.Name;
            }
        }

        return dicRelation;
    }

最后,您可以使用该字典并在您的方法中执行以下操作:

    public static bool CheckPropertyCompare(CustomerModel customer, Exclude item)
    {
        var dicRelation = getRelationPropertyAttribute(typeof(CustomerModel));

        var propertyName = dicRelation[item.SourceCol];
        var propertyValue = GetPropValue(customer, propertyName);
        return item.Values.Value.ToList().Contains(propertyValue);

    }

这是一个想法......希望它有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM