AttributeUsageAttribute.Inherited Свойство
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает или задает значение Boolean, определяющее, наследуется ли указанный атрибут производными классами и переопределяющими элементами.
public:
property bool Inherited { bool get(); void set(bool value); };
public bool Inherited { get; set; }
member this.Inherited : bool with get, set
Public Property Inherited As Boolean
Значение свойства
Возвращает значение true, если атрибут может наследоваться производными классами и переопределяющими элементами. В противном случае — значение false. Значение по умолчанию — true.
Примеры
В следующем примере показано различие между атрибутом, к которому AttributeUsageAttribute применяется атрибут со Inherited значением true свойства, и к которому AttributeUsageAttribute применяется атрибут со Inherited значением false свойства. В примере определяются два атрибута и InheritedAttribute NotInheritedAttribute. Оба атрибута могут применяться к классам и методам. Inherited Поскольку свойство атрибутаAttributeUsageAttribute, к которому применяетсяtrue``InheritedAttribute, оно наследуется производными классами и членами производных классов, которые переопределяют метод базового класса. С другой стороны, поскольку Inherited свойство атрибута AttributeUsageAttribute , к которому применяется NotInheritedAttribute false, не наследуется производными классами и членами производных классов, которые переопределяют метод базового класса.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Field,
Inherited = true)]
public class InheritedAttribute : Attribute
{ }
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Field,
Inherited = false)]
public class NotInheritedAttribute : Attribute
{ }
[<AttributeUsage(AttributeTargets.Class ||| AttributeTargets.Method ||| AttributeTargets.Property ||| AttributeTargets.Field, Inherited = true)>]
type InheritedAttribute() =
inherit Attribute()
[<AttributeUsage(AttributeTargets.Class ||| AttributeTargets.Method ||| AttributeTargets.Property ||| AttributeTargets.Field, Inherited = false)>]
type NotInheritedAttribute() =
inherit Attribute()
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method _
Or AttributeTargets.Property Or AttributeTargets.Field,
Inherited:=True)>
Public Class InheritedAttribute : Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method _
Or AttributeTargets.Property Or AttributeTargets.Field,
Inherited:=False)>
Public Class NotInheritedAttribute : Inherits Attribute
End Class
Затем в примере определяются два базовых класса. Во-первых, BaseAимеет один метод. MethodA Второй, BaseBимеет один метод. MethodB BaseAи MethodA помечены атрибутом MethodB InheritedAttribute BaseB и помечены атрибутом.NotInheritedAttribute DerivedA наследует от BaseA метода и переопределяет его MethodA метод. DerivedB наследует от BaseB метода и переопределяет его MethodB метод.
using System;
using System.Reflection;
[InheritedAttribute]
public class BaseA
{
[InheritedAttribute]
public virtual void MethodA()
{ }
}
public class DerivedA : BaseA
{
public override void MethodA()
{ }
}
[NotInheritedAttribute]
public class BaseB
{
[NotInheritedAttribute]
public virtual void MethodB()
{ }
}
public class DerivedB : BaseB
{
public override void MethodB()
{ }
}
public class Example
{
public static void Main()
{
Type typeA = typeof(DerivedA);
Console.WriteLine($"DerivedA has Inherited attribute: {typeA.GetCustomAttributes(typeof(InheritedAttribute), true).Length > 0}");
MethodInfo memberA = typeA.GetMethod(nameof(DerivedA.MethodA));
Console.WriteLine($"DerivedA.MemberA has Inherited attribute: {memberA.GetCustomAttributes(typeof(InheritedAttribute), true).Length > 0}\n");
Type typeB = typeof(DerivedB);
Console.WriteLine($"DerivedB has NotInherited attribute: {typeB.GetCustomAttributes(typeof(NotInheritedAttribute), true).Length > 0}");
MethodInfo memberB = typeB.GetMethod(nameof(DerivedB.MethodB));
Console.WriteLine($"DerivedB.MemberB has NotInherited attribute: {memberB.GetCustomAttributes(typeof(NotInheritedAttribute), true).Length > 0}");
}
}
// The example displays the following output:
// DerivedA has Inherited attribute: True
// DerivedA.MemberA has Inherited attribute: True
//
// DerivedB has NotInherited attribute: False
// DerivedB.MemberB has NotInherited attribute: False
[<Inherited>]
type BaseA() =
abstract member MethodA: unit -> unit
[<Inherited>]
default _.MethodA() = ()
type DerivedA() =
inherit BaseA()
override _.MethodA() = ()
[<NotInherited>]
type BaseB() =
abstract member MethodB: unit -> unit
[<NotInherited>]
default _.MethodB() = ()
type DerivedB() =
inherit BaseB()
override _.MethodB() = ()
let typeA = typeof<DerivedA>
printfn $"DerivedA has Inherited attribute: {typeA.GetCustomAttributes(typeof<InheritedAttribute>, true).Length > 0}"
let memberA = typeA.GetMethod "MethodA"
printfn $"DerivedA.MemberA has Inherited attribute: {memberA.GetCustomAttributes(typeof<InheritedAttribute>, true).Length > 0}\n"
let typeB = typeof<DerivedB>
printfn $"DerivedB has NotInherited attribute: {typeB.GetCustomAttributes(typeof<NotInheritedAttribute>, true).Length > 0}"
let memberB = typeB.GetMethod "MethodB"
printfn $"DerivedB.MemberB has NotInherited attribute: {memberB.GetCustomAttributes(typeof<NotInheritedAttribute>, true).Length > 0}"
// The example displays the following output:
// DerivedA has Inherited attribute: True
// DerivedA.MemberA has Inherited attribute: True
//
// DerivedB has NotInherited attribute: False
// DerivedB.MemberB has NotInherited attribute: False
Imports System.Reflection
<InheritedAttribute> Public Class BaseA
<InheritedAttribute> Public Overridable Sub MethodA()
End Sub
End Class
Public Class DerivedA : Inherits BaseA
Public Overrides Sub MethodA()
End Sub
End Class
<NotInheritedAttribute> Public Class BaseB
<NotInheritedAttribute> Public Overridable Sub MethodB()
End Sub
End Class
Public Class DerivedB : Inherits BaseB
Public Overrides Sub MethodB()
End Sub
End Class
Module Example
Public Sub Main()
Dim typeA As Type = GetType(DerivedA)
Console.WriteLine($"DerivedA has Inherited attribute: {typeA.GetCustomAttributes(GetType(InheritedAttribute), True).Length > 0}")
Dim memberA As MethodInfo = typeA.GetMethod(NameOf(DerivedA.MethodA))
Console.WriteLine($"DerivedA.MemberA has Inherited attribute: {memberA.GetCustomAttributes(GetType(InheritedAttribute), True).Length > 0}")
Console.WriteLine()
Dim typeB As Type = GetType(DerivedB)
Console.WriteLine($"DerivedB has NotInherited attribute: {typeB.GetCustomAttributes(GetType(NotInheritedAttribute), True).Length > 0}")
Dim memberB As MethodInfo = typeB.GetMethod(NameOf(DerivedB.MethodB))
Console.WriteLine($"DerivedB.MemberB has Inherited attribute: {memberB.GetCustomAttributes(GetType(NotInheritedAttribute), True).Length > 0}")
End Sub
End Module
' The example displays the following output:
' DerivedA has Inherited attribute: True
' DerivedA.MemberA has Inherited attribute: True
'
' DerivedB has Inherited attribute: False
' DerivedB.MemberB has Inherited attribute: False
Как показано в выходных данных примера, DerivedA и наследуйте атрибут, но DerivedB.MethodB DerivedB не наследуйте InheritedAttribute NotInheritedAttribute DerivedA.MethodA атрибут.
Комментарии
Свойство Inherited определяет:
Указывает, наследуют ли классы, производные от базового класса, помеченного атрибутом, к которому AttributeUsageAttribute применяется атрибут.
Указывает, наследуют ли методы производных классов, которые переопределяют метод базового класса, помеченный атрибутом, к которому AttributeUsageAttribute применяется атрибут. (Если класс наследует элемент базового класса, он также наследует все атрибуты, примененные к данному члену.)