【发布时间】:2019-05-15 15:05:54
【问题描述】:
我想获取由属性 AggregateAuthorizeIdentifier 修饰的所有属性。它是核心功能,所以应该尽可能快。
我可以通过所有属性进行递归搜索,但我会检查所有系统和第 3 方库。但这不是最佳解决方案。
你遇到过这样的问题吗?
public class ReadOrderHistoryQuery
{
public List<string> Ordering { get; set; }
public Criteria Criteria { get; set; }
public class Criteria
{
[AggregateAuthorizeIdentifier]
public int UserId { get; set; }
public string InvoiceId { get; set; }
}
}
我的解决方案:
static IEnumerable<PropertyWithAttribute> GetAuthorizeIdentifierAttribute(object command)
{
var attributedProperties = GetAuthorizeIdentifierAttribute(command.GetType());
return attributedProperties;
}
static IEnumerable<PropertyWithAttribute> GetAuthorizeIdentifierAttribute(Type type)
{
//check current property
var result = type.GetProperties()
.Where(prop => Attribute.IsDefined(prop, typeof(AggregateAuthorizeIdentifierAttribute)))
.Select(p => new PropertyWithAttribute()
{
Property = p,
Attribute = p.GetCustomAttribute<AggregateAuthorizeIdentifierAttribute>(true)
})
.ToList();
//deeper check all properties
result.AddRange(type.GetProperties()
.SelectMany(p => GetAuthorizeIdentifierAttribute(p.PropertyType)));
return result;
}
【问题讨论】:
-
But it isn't optimal solution.你为什么这么认为? -
我的解决方案搜索通过所有系统属性,如字符串、列表等和第 3 方。这是完全没有必要的。
标签: c# .net recursion reflection attributes