Может ли класс C# наследовать атрибуты своего интерфейса?
Вы можете определить полезный attributes метод расширения ...
Type type = typeof(ProjectController);
var attributes = type.GetCustomAttributes( true );
Вот метод c# расширения:
/// Searches and returns attributes. The inheritance chain is not used to find the attributes.
/// The type of attribute to search for.
/// The type which is searched for the attributes.
/// Returns all attributes.
public static T[] GetCustomAttributes( this Type type ) where T : Attribute
{
return GetCustomAttributes( type, typeof( T ), false ).Select( arg => (T)arg ).ToArray();
}
/// Searches and returns attributes.
/// The type of attribute to search for.
/// The type which is searched for the attributes.
/// Specifies whether to search this member's inheritance chain to find the attributes. Interfaces will be searched, too.
/// Returns all attributes.
public static T[] GetCustomAttributes( this Type type, bool inherit ) where T : Attribute
{
return GetCustomAttributes( type, typeof( T ), inherit ).Select( arg => (T)arg ).ToArray();
}
/// Private helper for searching attributes.
/// The type which is searched for the attribute.
/// The type of attribute to search for.
/// Specifies whether to search this member's inheritance chain to find the attribute. Interfaces will be searched, too.
/// An array that contains all the custom attributes, or an array with zero elements if no attributes are defined.
private static object[] GetCustomAttributes( Type type, Type attributeType, bool inherit )
{
if( !inherit )
{
return type.GetCustomAttributes( attributeType, false );
}
var attributeCollection = new Collection
Обновление:
Вот более короткая c-sharp версия, предложенная SimonD csharp в комментарии:
private static IEnumerable GetCustomAttributesIncludingBaseInterfaces(this Type type)
{
var attributeType = typeof(T);
return type.GetCustomAttributes(attributeType, true)
.Union(type.GetInterfaces().SelectMany(interfaceType =>
interfaceType.GetCustomAttributes(attributeType, true)))
.Cast();
}
c#
attributes
2021-12-15T04:48:51+00:00
2022-11-17T08:33:44+00:00
junpython
Вопросы с похожей тематикой, как у вопроса:
Может ли класс C# наследовать атрибуты своего интерфейса?
Предупреждение о файлах Cookies
Мы используем файлы cookies для улучшения работы сайта. Оставаясь на нашем сайте, вы соглашаетесь с условиями использования файлов cookies. Чтобы ознакомиться с нашими Положениями о конфиденциальности и об использовании файлов cookie, нажмите здесь.