我有方法
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
已经有(扩展)方法GetCustomAttributes<T>()