Может ли класс 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();
  var baseType = type;

  do
  {
    baseType.GetCustomAttributes( attributeType, true ).Apply( attributeCollection.Add );
    baseType = baseType.BaseType;
  }
  while( baseType != null );

  foreach( var interfaceType in type.GetInterfaces() )
  {
    GetCustomAttributes( interfaceType, attributeType, true ).Apply( attributeCollection.Add );
  }

  var attributeArray = new object[attributeCollection.Count];
  attributeCollection.CopyTo( attributeArray, 0 );
  return attributeArray;
}

/// Applies a function to every element of the list.
private static void Apply( this IEnumerable enumerable, Action function )
{
  foreach( var item in enumerable )
  {
    function.Invoke( item );
  }
}

Обновление:

Вот более короткая 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

2022-11-17T08:33:44+00:00
Вопросы с похожей тематикой, как у вопроса:

Может ли класс C# наследовать атрибуты своего интерфейса?