Свойство Inherited
По умолчанию Inherited
равно true: атрибут
базового класса находят у
наследника с inherit: true.
При false у наследника
результат null.
Синтаксис
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
class SealAttribute : Attribute
{
}
Пример
Давайте найти атрибут базы у наследника с наследованием:
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class)]
class MarkAttribute : Attribute
{
}
[Mark]
class BaseType
{
}
class DerivedType : BaseType
{
}
class Program
{
static void Main()
{
MarkAttribute mark = typeof(DerivedType)
.GetCustomAttribute<MarkAttribute>(inherit: true);
bool res = mark != null;
Console.WriteLine(res);
}
}
Результат выполнения кода:
True
Пример
Давайте скрыть атрибут от
наследника через
Inherited = false:
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
class SealAttribute : Attribute
{
}
[Seal]
class BaseType
{
}
class DerivedType : BaseType
{
}
class Program
{
static void Main()
{
SealAttribute seal = typeof(DerivedType)
.GetCustomAttribute<SealAttribute>(inherit: true);
bool res = seal == null;
Console.WriteLine(res);
}
}
Результат выполнения кода:
True
Пример
Давайте прочитать Inherited
по умолчанию у атрибута:
using System;
[AttributeUsage(AttributeTargets.Class)]
class MarkAttribute : Attribute
{
}
class Program
{
static void Main()
{
AttributeUsageAttribute usage = (AttributeUsageAttribute)
Attribute.GetCustomAttribute(
typeof(MarkAttribute),
typeof(AttributeUsageAttribute));
bool res = usage.Inherited;
Console.WriteLine(res);
}
}
Результат выполнения кода:
True
Смотрите также
-
AttributeUsage,
цели -
AllowMultiple,
несколько раз -
Attribute,
базовый класс -
Obsolete,
устаревшее