您可以創建一個簡單的擴展方法將從ICustomAttributeProvider
interface的實現(這是由一個.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
method,並通過上述查詢運行它以獲取PropertyInfo
實例和應用於該實例的屬性。