您可以创建一个简单的扩展方法,该方法将从接口的实现中获取所需的属性(该ICustomAttributeProvider
接口由可以具有属性的 .NET 构造的任何表示形式实现):
public static IEnumerable<T> GetCustomAttributes(
this ICustomAttributeProvider provider, bool inherit) where T : Attribute
{
// Validate parameters.
if (provider == null) throw new ArgumentNullException("provider");
// Get custom attributes.
return provider.GetCustomAttributes(typeof(T), inherit).
Cast<T>();
}
从那里,它是PropertyInfo
一个类型上所有实例的调用,如下所示:
var attributes =
// Get all public properties, you might want to
// call a more specific overload based on your needs.
from p in obj.GetType().GetProperties()
// Get the attribute.
let attribute = p.GetCustomAttributes<GridColumnAttribute>().
// Assuming allow multiple is false.
SingleOrDefault().
// Filter out null properties.
where attribute != null
// Map property with attribute.
select new { Property = p, Attribute = attribute };
从那里,您可以在任何对象实例上调用该GetType
方法并通过上述查询运行它以获取PropertyInfo
实例和应用于它的属性。