CustomAttributeData Osztály
Definíció
Fontos
Egyes információk olyan, kiadás előtti termékekre vonatkoznak, amelyek a kiadásig még jelentősen módosulhatnak. A Microsoft nem vállal kifejezett vagy törvényi garanciát az itt megjelenő információért.
Hozzáférést biztosít az egyéni attribútumadatokhoz a csak tükrözési környezetbe betöltött szerelvényekhez, modulokhoz, típusokhoz, tagokhoz és paraméterekhez.
public ref class CustomAttributeData
public ref class CustomAttributeData sealed
public class CustomAttributeData
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class CustomAttributeData
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class CustomAttributeData
type CustomAttributeData = class
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Serializable>]
type CustomAttributeData = class
Public Class CustomAttributeData
Public NotInheritable Class CustomAttributeData
- Öröklődés
-
CustomAttributeData
- Attribútumok
Példák
Az alábbi példa egy négy konstruktort és négy tulajdonságot tartalmazó egyéni attribútumot határoz meg. A tulajdonságok közül kettő írásvédett, és a konstruktorok pozícióparamétereinek használatával van beállítva. A másik két tulajdonság az olvasás/írás, és csak névvel ellátott argumentumok használatával állítható be. Az egyik pozíciótulajdonság sztringek tömbje, egy elnevezett tulajdonság pedig egész számok tömbje.
Az attribútum a szerelvényre, a szerelvényben deklarált típusra, a típus metódusára és a metódus egy paraméterére lesz alkalmazva. Ezekhez az esetekhez különböző konstruktorok használhatók. A végrehajtáskor a szerelvény betölti magát a csak tükröződési környezetbe, és megjeleníti a rá alkalmazott egyéni attribútumokra, valamint a benne lévő típusra és tagokra vonatkozó információkat.
A típusra alkalmazott attribútum a tömbtulajdonságokat mutatja be pozíció- és elnevezett argumentumokkal.
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Collections.ObjectModel;
// The example attribute is applied to the assembly.
[assembly:Example(ExampleKind.ThirdKind, Note="This is a note on the assembly.")]
// An enumeration used by the ExampleAttribute class.
public enum ExampleKind
{
FirstKind,
SecondKind,
ThirdKind,
FourthKind
};
// An example attribute. The attribute can be applied to all
// targets, from assemblies to parameters.
//
[AttributeUsage(AttributeTargets.All)]
public class ExampleAttribute : Attribute
{
// Data for properties.
private ExampleKind kindValue;
private string noteValue;
private string[] arrayStrings;
private int[] arrayNumbers;
// Constructors. The parameterless constructor (.ctor) calls
// the constructor that specifies ExampleKind and an array of
// strings, and supplies the default values.
//
public ExampleAttribute(ExampleKind initKind, string[] initStrings)
{
kindValue = initKind;
arrayStrings = initStrings;
}
public ExampleAttribute(ExampleKind initKind) : this(initKind, null) {}
public ExampleAttribute() : this(ExampleKind.FirstKind, null) {}
// Properties. The Note and Numbers properties must be read/write, so they
// can be used as named parameters.
//
public ExampleKind Kind { get { return kindValue; }}
public string[] Strings { get { return arrayStrings; }}
public string Note
{
get { return noteValue; }
set { noteValue = value; }
}
public int[] Numbers
{
get { return arrayNumbers; }
set { arrayNumbers = value; }
}
}
// The example attribute is applied to the test class.
//
[Example(ExampleKind.SecondKind,
new string[] { "String array argument, line 1",
"String array argument, line 2",
"String array argument, line 3" },
Note="This is a note on the class.",
Numbers = new int[] { 53, 57, 59 })]
public class Test
{
// The example attribute is applied to a method, using the
// parameterless constructor and supplying a named argument.
// The attribute is also applied to the method parameter.
//
[Example(Note="This is a note on a method.")]
public void TestMethod([Example] object arg) { }
// Main() gets objects representing the assembly, the test
// type, the test method, and the method parameter. Custom
// attribute data is displayed for each of these.
//
public static void Main()
{
Assembly asm = Assembly.ReflectionOnlyLoad("Source");
Type t = asm.GetType("Test");
MethodInfo m = t.GetMethod("TestMethod");
ParameterInfo[] p = m.GetParameters();
Console.WriteLine("\r\nAttributes for assembly: '{0}'", asm);
ShowAttributeData(CustomAttributeData.GetCustomAttributes(asm));
Console.WriteLine("\r\nAttributes for type: '{0}'", t);
ShowAttributeData(CustomAttributeData.GetCustomAttributes(t));
Console.WriteLine("\r\nAttributes for member: '{0}'", m);
ShowAttributeData(CustomAttributeData.GetCustomAttributes(m));
Console.WriteLine("\r\nAttributes for parameter: '{0}'", p);
ShowAttributeData(CustomAttributeData.GetCustomAttributes(p[0]));
}
private static void ShowAttributeData(
IList<CustomAttributeData> attributes)
{
foreach( CustomAttributeData cad in attributes )
{
Console.WriteLine(" {0}", cad);
Console.WriteLine(" Constructor: '{0}'", cad.Constructor);
Console.WriteLine(" Constructor arguments:");
foreach( CustomAttributeTypedArgument cata
in cad.ConstructorArguments )
{
ShowValueOrArray(cata);
}
Console.WriteLine(" Named arguments:");
foreach( CustomAttributeNamedArgument cana
in cad.NamedArguments )
{
Console.WriteLine(" MemberInfo: '{0}'",
cana.MemberInfo);
ShowValueOrArray(cana.TypedValue);
}
}
}
private static void ShowValueOrArray(CustomAttributeTypedArgument cata)
{
if (cata.Value.GetType() == typeof(ReadOnlyCollection<CustomAttributeTypedArgument>))
{
Console.WriteLine(" Array of '{0}':", cata.ArgumentType);
foreach (CustomAttributeTypedArgument cataElement in
(ReadOnlyCollection<CustomAttributeTypedArgument>) cata.Value)
{
Console.WriteLine(" Type: '{0}' Value: '{1}'",
cataElement.ArgumentType, cataElement.Value);
}
}
else
{
Console.WriteLine(" Type: '{0}' Value: '{1}'",
cata.ArgumentType, cata.Value);
}
}
}
/* This code example produces output similar to the following:
Attributes for assembly: 'source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
[System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)]
Constructor: 'Void .ctor(Int32)'
Constructor arguments:
Type: 'System.Int32' Value: '8'
Named arguments:
[System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows = True)]
Constructor: 'Void .ctor()'
Constructor arguments:
Named arguments:
MemberInfo: 'Boolean WrapNonExceptionThrows'
Type: 'System.Boolean' Value: 'True'
[ExampleAttribute((ExampleKind)2, Note = "This is a note on the assembly.")]
Constructor: 'Void .ctor(ExampleKind)'
Constructor arguments:
Type: 'ExampleKind' Value: '2'
Named arguments:
MemberInfo: 'System.String Note'
Type: 'System.String' Value: 'This is a note on the assembly.'
Attributes for type: 'Test'
[ExampleAttribute((ExampleKind)1, new String[3] { "String array argument, line 1", "String array argument, line 2", "String array argument, line 3" }, Note = "This is a note on the class.", Numbers = new Int32[3] { 53, 57, 59 })]
Constructor: 'Void .ctor(ExampleKind, System.String[])'
Constructor arguments:
Type: 'ExampleKind' Value: '1'
Array of 'System.String[]':
Type: 'System.String' Value: 'String array argument, line 1'
Type: 'System.String' Value: 'String array argument, line 2'
Type: 'System.String' Value: 'String array argument, line 3'
Named arguments:
MemberInfo: 'System.String Note'
Type: 'System.String' Value: 'This is a note on the class.'
MemberInfo: 'Int32[] Numbers'
Array of 'System.Int32[]':
Type: 'System.Int32' Value: '53'
Type: 'System.Int32' Value: '57'
Type: 'System.Int32' Value: '59'
Attributes for member: 'Void TestMethod(System.Object)'
[ExampleAttribute(Note = "This is a note on a method.")]
Constructor: 'Void .ctor()'
Constructor arguments:
Named arguments:
MemberInfo: 'System.String Note'
Type: 'System.String' Value: 'This is a note on a method.'
Attributes for parameter: 'System.Object arg'
[ExampleAttribute()]
Constructor: 'Void .ctor()'
Constructor arguments:
Named arguments:
*/
Imports System.Reflection
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
' The example attribute is applied to the assembly.
<Assembly:Example(ExampleKind.ThirdKind, Note:="This is a note on the assembly.")>
' An enumeration used by the ExampleAttribute class.
Public Enum ExampleKind
FirstKind
SecondKind
ThirdKind
FourthKind
End Enum
' An example attribute. The attribute can be applied to all
' targets, from assemblies to parameters.
'
<AttributeUsage(AttributeTargets.All)> _
Public Class ExampleAttribute
Inherits Attribute
' Data for properties.
Private kindValue As ExampleKind
Private noteValue As String
Private arrayStrings() As String
Private arrayNumbers() As Integer
' Constructors. The parameterless constructor (.ctor) calls
' the constructor that specifies ExampleKind and an array of
' strings, and supplies the default values.
'
Public Sub New(ByVal initKind As ExampleKind, ByVal initStrings() As String)
kindValue = initKind
arrayStrings = initStrings
End Sub
Public Sub New(ByVal initKind As ExampleKind)
Me.New(initKind, Nothing)
End Sub
Public Sub New()
Me.New(ExampleKind.FirstKind, Nothing)
End Sub
' Properties. The Note and Numbers properties must be read/write, so they
' can be used as named parameters.
'
Public ReadOnly Property Kind As ExampleKind
Get
Return kindValue
End Get
End Property
Public ReadOnly Property Strings As String()
Get
Return arrayStrings
End Get
End Property
Public Property Note As String
Get
Return noteValue
End Get
Set
noteValue = value
End Set
End Property
Public Property Numbers As Integer()
Get
Return arrayNumbers
End Get
Set
arrayNumbers = value
End Set
End Property
End Class
' The example attribute is applied to the test class.
'
<Example(ExampleKind.SecondKind, _
New String() { "String array argument, line 1", _
"String array argument, line 2", _
"String array argument, line 3" }, _
Note := "This is a note on the class.", _
Numbers := New Integer() { 53, 57, 59 })> _
Public Class Test
' The example attribute is applied to a method, using the
' parameterless constructor and supplying a named argument.
' The attribute is also applied to the method parameter.
'
<Example(Note:="This is a note on a method.")> _
Public Sub TestMethod(<Example()> ByVal arg As Object)
End Sub
' Sub Main gets objects representing the assembly, the test
' type, the test method, and the method parameter. Custom
' attribute data is displayed for each of these.
'
Public Shared Sub Main()
Dim asm As [Assembly] = Assembly.ReflectionOnlyLoad("source")
Dim t As Type = asm.GetType("Test")
Dim m As MethodInfo = t.GetMethod("TestMethod")
Dim p() As ParameterInfo = m.GetParameters()
Console.WriteLine(vbCrLf & "Attributes for assembly: '{0}'", asm)
ShowAttributeData(CustomAttributeData.GetCustomAttributes(asm))
Console.WriteLine(vbCrLf & "Attributes for type: '{0}'", t)
ShowAttributeData(CustomAttributeData.GetCustomAttributes(t))
Console.WriteLine(vbCrLf & "Attributes for member: '{0}'", m)
ShowAttributeData(CustomAttributeData.GetCustomAttributes(m))
Console.WriteLine(vbCrLf & "Attributes for parameter: '{0}'", p)
ShowAttributeData(CustomAttributeData.GetCustomAttributes(p(0)))
End Sub
Private Shared Sub ShowAttributeData( _
ByVal attributes As IList(Of CustomAttributeData))
For Each cad As CustomAttributeData _
In CType(attributes, IEnumerable(Of CustomAttributeData))
Console.WriteLine(" {0}", cad)
Console.WriteLine(" Constructor: '{0}'", cad.Constructor)
Console.WriteLine(" Constructor arguments:")
For Each cata As CustomAttributeTypedArgument _
In CType(cad.ConstructorArguments, IEnumerable(Of CustomAttributeTypedArgument))
ShowValueOrArray(cata)
Next
Console.WriteLine(" Named arguments:")
For Each cana As CustomAttributeNamedArgument _
In CType(cad.NamedArguments, IEnumerable(Of CustomAttributeNamedArgument))
Console.WriteLine(" MemberInfo: '{0}'", _
cana.MemberInfo)
ShowValueOrArray(cana.TypedValue)
Next
Next
End Sub
Private Shared Sub ShowValueOrArray(ByVal cata As CustomAttributeTypedArgument)
If cata.Value.GetType() Is GetType(ReadOnlyCollection(Of CustomAttributeTypedArgument)) Then
Console.WriteLine(" Array of '{0}':", cata.ArgumentType)
For Each cataElement As CustomAttributeTypedArgument In cata.Value
Console.WriteLine(" Type: '{0}' Value: '{1}'", _
cataElement.ArgumentType, cataElement.Value)
Next
Else
Console.WriteLine(" Type: '{0}' Value: '{1}'", _
cata.ArgumentType, cata.Value)
End If
End Sub
End Class
' This code example produces output similar to the following:
'
'Attributes for assembly: 'source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
' [System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)]
' Constructor: 'Void .ctor(Int32)'
' Constructor arguments:
' Type: 'System.Int32' Value: '8'
' Named arguments:
' [System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows = True)]
' Constructor: 'Void .ctor()'
' Constructor arguments:
' Named arguments:
' MemberInfo: 'Boolean WrapNonExceptionThrows'
' Type: 'System.Boolean' Value: 'True'
' [ExampleAttribute((ExampleKind)2, Note = "This is a note on the assembly.")]
' Constructor: 'Void .ctor(ExampleKind)'
' Constructor arguments:
' Type: 'ExampleKind' Value: '2'
' Named arguments:
' MemberInfo: 'System.String Note'
' Type: 'System.String' Value: 'This is a note on the assembly.'
'
'Attributes for type: 'Test'
' [ExampleAttribute((ExampleKind)1, new String[3] { "String array argument, line 1", "String array argument, line 2", "String array argument, line 3" }, Note = "This is a note on the class.", Numbers = new Int32[3] { 53, 57, 59 })]
' Constructor: 'Void .ctor(ExampleKind, System.String[])'
' Constructor arguments:
' Type: 'ExampleKind' Value: '1'
' Array of 'System.String[]':
' Type: 'System.String' Value: 'String array argument, line 1'
' Type: 'System.String' Value: 'String array argument, line 2'
' Type: 'System.String' Value: 'String array argument, line 3'
' Named arguments:
' MemberInfo: 'System.String Note'
' Type: 'System.String' Value: 'This is a note on the class.'
' MemberInfo: 'Int32[] Numbers'
' Array of 'System.Int32[]':
' Type: 'System.Int32' Value: '53'
' Type: 'System.Int32' Value: '57'
' Type: 'System.Int32' Value: '59'
'
'Attributes for member: 'Void TestMethod(System.Object)'
' [ExampleAttribute(Note = "This is a note on a method.")]
' Constructor: 'Void .ctor()'
' Constructor arguments:
' Named arguments:
' MemberInfo: 'System.String Note'
' Type: 'System.String' Value: 'This is a note on a method.'
'
'Attributes for parameter: 'System.Object arg'
' [ExampleAttribute()]
' Constructor: 'Void .ctor()'
' Constructor arguments:
' Named arguments:
Megjegyzések
A csak tükröződés kontextusában vizsgált kód nem hajtható végre, így nem mindig lehet egyéni attribútumokat megvizsgálni példányok létrehozásával, majd tulajdonságaik vizsgálatával, például Attribute.GetCustomAttributesa , MemberInfo.GetCustomAttributesstb. metódusok használatával. Ha magát az attribútumtípust a rendszer betölti a csak tükröződési környezetbe, akkor az nem hajtható végre.
Az CustomAttributeData osztály lehetővé teszi az egyéni attribútumok vizsgálatát a csak tükröződési kontextusban azáltal, hogy absztrakciót biztosít az attribútumokhoz. Az osztály tagjai az attribútum pozícióargumentumainak és elnevezett argumentumainak lekérésére használhatók. ConstructorArguments A tulajdonság használatával lekérheti a pozícióargumentumokat képviselő struktúrák listájátCustomAttributeTypedArgument, a tulajdonság használatával NamedArguments pedig lekérheti az elnevezett argumentumokat képviselő struktúrák listájátCustomAttributeNamedArgument.
Note
A CustomAttributeNamedArgument struktúra csak az argumentumérték lekéréséhez és beállításához használt attribútumtulajdonságról nyújt információt. Az argumentum típusának és értékének lekéréséhez használja a CustomAttributeNamedArgument.TypedValue tulajdonságot egy CustomAttributeTypedArgument struktúra beszerzéséhez.
Ha egy argumentum struktúrája elnevezett CustomAttributeTypedArgument vagy pozíciós, a CustomAttributeTypedArgument.ArgumentType tulajdonság használatával kérje le a típust és a CustomAttributeTypedArgument.Value tulajdonságot az érték lekéréséhez.
Note
Tömbargumentum esetén a tulajdonság az CustomAttributeTypedArgument.Value objektumok általános ReadOnlyCollection<T> értékét CustomAttributeTypedArgument adja vissza. A gyűjtemény minden CustomAttributeTypedArgument objektuma a tömb megfelelő elemét jelöli.
CustomAttributeData használható a végrehajtási környezetben és a csak tükrözési környezetben is. Előfordulhat például, hogy nem szeretné betölteni az egyéni attribútum kódját tartalmazó szerelvényt. CustomAttributeData Az osztály használata eltér az alábbi Attribute.GetCustomAttributesmódszerektől:
A tulajdonságok és metódusok CustomAttributeData csak az attribútumpéldányhoz megadott értékeket biztosítják, a konstruktor szemantikáját nem. Előfordulhat például, hogy egy attribútum sztringargumentumát belsőleg más megjelenítésre konvertálják, és canonikus formában adják vissza; vagy egy tulajdonságnak lehetnek mellékhatásai a tényleges attribútumkód végrehajtásakor.
A tulajdonságok és metódusok CustomAttributeData nem teszik lehetővé az alaposztályoktól örökölt egyéni attribútumok lekérését.
A CustomAttributeData osztály példányainak létrehozásához használja a static (Shared Visual Basic) GetCustomAttributes gyári metódusokat.
Konstruktorok
| Name | Description |
|---|---|
| CustomAttributeData() |
Inicializálja a CustomAttributeData osztály új példányát. |
Tulajdonságok
| Name | Description |
|---|---|
| AttributeType |
Lekéri az attribútum típusát. |
| Constructor |
ConstructorInfo Lekéri azt az objektumot, amely azt a konstruktort jelöli, amely inicializálta volna az egyéni attribútumot. |
| ConstructorArguments |
Lekéri az objektum által CustomAttributeData képviselt attribútumpéldányhoz megadott pozícióargumentumok listáját. |
| NamedArguments |
Lekéri az objektum által CustomAttributeData képviselt attribútumpéldányhoz megadott elnevezett argumentumok listáját. |
Metódusok
| Name | Description |
|---|---|
| Equals(Object) |
Olyan értéket ad vissza, amely jelzi, hogy ez a példány egyenlő-e egy adott objektummal. |
| Equals(Object) |
Meghatározza, hogy a megadott objektum egyenlő-e az aktuális objektummal. (Öröklődés forrása Object) |
| GetCustomAttributes(Assembly) |
Visszaadja a CustomAttributeData célszerelvényre alkalmazott attribútumok adatait képviselő objektumok listáját. |
| GetCustomAttributes(MemberInfo) |
Visszaadja a CustomAttributeData céltagra alkalmazott attribútumok adatait képviselő objektumok listáját. |
| GetCustomAttributes(Module) |
A célmodulra alkalmazott attribútumokkal kapcsolatos adatokat képviselő objektumok listáját CustomAttributeData adja vissza. |
| GetCustomAttributes(ParameterInfo) |
Visszaadja a CustomAttributeData célparaméterre alkalmazott attribútumok adatait képviselő objektumok listáját. |
| GetHashCode() |
Egy adott típus kivonatfüggvénye. |
| GetHashCode() |
Ez az alapértelmezett kivonatoló függvény. (Öröklődés forrása Object) |
| GetType() |
Lekéri az Type aktuális példányt. (Öröklődés forrása Object) |
| MemberwiseClone() |
Az aktuális Objectpéldány sekély másolatát hozza létre. (Öröklődés forrása Object) |
| ToString() |
Az egyéni attribútum sztring-ábrázolását adja vissza. |
| ToString() |
Az aktuális objektumot jelképező sztringet ad vissza. (Öröklődés forrása Object) |