如何获取自定义属性的通用集合

阿米特·辛格

我有办法

 private static 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;

            for each (var attribute in custom attributes)
            {
                if (attribute is MongoDBFieldAttribute attr)
                    dicRelation[attr.Field] = property.Name;
            }
        }

        return dicRelation;
    }

在这种typeof(MongoDBFieldAttribute)中,仅使我具有MOngoDBFieldAttribute类型的所有属性的CustomAttributes列表,而我的属性为:

    [FieldIdentifier("SSI")]
    [MongoDBField("Sender State ID")]
    public string SenderStateID { get; set; }


    [FieldIdentifier("SPH")]
    [MongoDBField("Sender Phone")]
    public string SenderPhone { get; set; }

如何使该方法通用,以便根据需要获取MongoDBField或FieldIdentifier字典?

广州7

已经有一个(扩展)方法 GetCustomAttributes<T>()

所以你可以这样写:

using System.Reflection;

var customAttributes = property.GetCustomAttributes<MongoDBFieldAttribute>();

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

要使您的方法在属性类型上通用,并返回其中键是属性的字典:

private static Dictionary<T, string> getRelationPropertyAttribute<T>(Type type) where T : Attribute
{
    var dicRelation = new Dictionary<T, string>();

    var properties = type.GetProperties();
    foreach (var property in properties)
    {
        var customAttributes = property.GetCustomAttributes<T>();
        foreach (var attribute in customAttributes)
        {
            dicRelation[attr] = property.Name;
        }
    }

    return dicRelation;
}

或者,您可以使用Linq使其更简洁:

private static Dictionary<T, string> getRelationPropertyAttribute<T>(Type type) where T : Attribute
{
    var pairs = from property in type.GetProperties()
                from attribute in property.GetCustomAttributes<T>()
                select new KeyValuePair<T, string>(attribute, property.Name);
    return new Dictionary<T, string>(pairs);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章