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

问题描述 投票:1回答:1

我有方法

 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)]中,我得到了所有属性的CustomAttributes列表,仅MOngoDBFieldAttribute类型,我的属性为:

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


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

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

我有一个方法私有静态Dictionary getRelationPropertyAttribute(Type type){var dicRelation = new Dictionary (); var ...

c# generics
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.