Vytváření vlastních atributů (C# and Visual Basic)
Můžete vytvořit vlastní atributy vlastní definice atributu třídy, třídy, která se odvozuje přímo nebo nepřímo z Attribute, které umožňuje identifikaci definice atributu v metadatech rychlé a snadné.Předpokládejme, že chcete typy značku s názvem programátor, který vytvořil typu.Můžete definovat vlastní Author atribut třídy:
<System.AttributeUsage(System.AttributeTargets.Class Or
System.AttributeTargets.Struct)>
Public Class Author
Inherits System.Attribute
Private name As String
Public version As Double
Sub New(ByVal authorName As String)
name = authorName
version = 1.0
End Sub
End Class
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct)
]
public class Author : System.Attribute
{
private string name;
public double version;
public Author(string name)
{
this.name = name;
version = 1.0;
}
}
Název třídy je název atributu, Author.Je odvozen z System.Attribute, takže je vlastní třída atributu.Vlastní atribut poziční parametry jsou konstruktoru parametry.V tomto příkladu name je poziční parametr.Parametry jsou pojmenovány žádné vlastnosti nebo veřejná pole pro čtení i zápis.V tomto případě version pouze názvem parametru.Poznámka: použití AttributeUsage atribut tak, aby Author atributu je platný pouze pro třídy a struct (Structure v jazyce Visual Basic) prohlášení.
Tento nový atribut nelze použít takto:
<Author("P. Ackerman", Version:=1.1)>
Class SampleClass
' P. Ackerman's code goes here...
End Class
[Author("P. Ackerman", version = 1.1)]
class SampleClass
{
// P. Ackerman's code goes here...
}
AttributeUsagebyl pojmenovaný parametr AllowMultiple, s níž můžete vytvořit vlastní atribut, jedno použití nebo multiuse.Následující příklad kódu je vytvořen multiuse atributu.
' multiuse attribute
<System.AttributeUsage(System.AttributeTargets.Class Or
System.AttributeTargets.Struct,
AllowMultiple:=True)>
Public Class Author
Inherits System.Attribute
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct,
AllowMultiple = true) // multiuse attribute
]
public class Author : System.Attribute
V následujícím příkladu kódu více atributů stejného typu u třídy.
<Author("P. Ackerman", Version:=1.1),
Author("R. Koch", Version:=1.2)>
Class SampleClass
' P. Ackerman's code goes here...
' R. Koch's code goes here...
End Class
[Author("P. Ackerman", version = 1.1)]
[Author("R. Koch", version = 1.2)]
class SampleClass
{
// P. Ackerman's code goes here...
// R. Koch's code goes here...
}
[!POZNÁMKA]
Pokud atribut třídy obsahuje vlastnost, musí být vlastnosti pro čtení i zápis.
Viz také
Referenční dokumentace
Atributy (C# and Visual Basic)
Přístup k atributům pomocí reflexe (C# and Visual Basic)
AttributeUsage (C# and Visual Basic)