Mengambil Informasi yang Disimpan di Atribut
Mengambil atribut kustom adalah proses yang sederhana. Pertama, deklarasikan instans atribut yang ingin Anda ambil. Kemudian, gunakan metode Attribute.GetCustomAttribute untuk menginisialisasi atribut baru ke nilai atribut yang ingin Anda ambil. Setelah atribut baru diinisialisasi, Anda dapat menggunakan propertinya untuk mendapatkan nilai.
Penting
Artikel ini menjelaskan cara mengambil atribut untuk kode yang dimuat ke dalam konteks eksekusi. Untuk mengambil atribut untuk kode yang dimuat ke dalam konteks refleksi-saja, Anda harus menggunakan kelas CustomAttributeData, seperti yang ditunjukkan dalam Cara: Memuat Rakitan ke dalam Konteks Refleksi-Saja.
Bagian ini menjelaskan cara-cara berikut untuk mengambil atribut:
Mengambil beberapa instans dari sebuah atribut yang diterapkan ke cakupan yang sama
Mengambil beberapa instans dari sebuah atribut yang diterapkan ke cakupan yang berbeda
Mengambil Satu Instans dari Sebuah Atribut
Dalam contoh berikut, DeveloperAttribute
(dijelaskan di bagian sebelumnya) diterapkan ke kelas MainApp
pada tingkat kelas. Metode ini GetAttribute
menggunakan GetCustomAttribute
untuk mengambil nilai yang disimpan di DeveloperAttribute
tingkat kelas sebelum menampilkannya ke konsol.
using namespace System;
using namespace System::Reflection;
using namespace CustomCodeAttributes;
[Developer("Joan Smith", "42", Reviewed = true)]
ref class MainApp
{
public:
static void Main()
{
// Call function to get and display the attribute.
GetAttribute(MainApp::typeid);
}
static void GetAttribute(Type^ t)
{
// Get instance of the attribute.
DeveloperAttribute^ MyAttribute =
(DeveloperAttribute^) Attribute::GetCustomAttribute(t, DeveloperAttribute::typeid);
if (MyAttribute == nullptr)
{
Console::WriteLine("The attribute was not found.");
}
else
{
// Get the Name value.
Console::WriteLine("The Name Attribute is: {0}." , MyAttribute->Name);
// Get the Level value.
Console::WriteLine("The Level Attribute is: {0}." , MyAttribute->Level);
// Get the Reviewed value.
Console::WriteLine("The Reviewed Attribute is: {0}." , MyAttribute->Reviewed);
}
}
};
using System;
using System.Reflection;
using CustomCodeAttributes;
[Developer("Joan Smith", "42", Reviewed = true)]
class MainApp
{
public static void Main()
{
// Call function to get and display the attribute.
GetAttribute(typeof(MainApp));
}
public static void GetAttribute(Type t)
{
// Get instance of the attribute.
DeveloperAttribute MyAttribute =
(DeveloperAttribute) Attribute.GetCustomAttribute(t, typeof (DeveloperAttribute));
if (MyAttribute == null)
{
Console.WriteLine("The attribute was not found.");
}
else
{
// Get the Name value.
Console.WriteLine("The Name Attribute is: {0}." , MyAttribute.Name);
// Get the Level value.
Console.WriteLine("The Level Attribute is: {0}." , MyAttribute.Level);
// Get the Reviewed value.
Console.WriteLine("The Reviewed Attribute is: {0}." , MyAttribute.Reviewed);
}
}
}
Imports System.Reflection
Imports CustomCodeAttributes
<Developer("Joan Smith", "42", Reviewed:=True)>
Class MainApp
Public Shared Sub Main()
' Call function to get and display the attribute.
GetAttribute(GetType(MainApp))
End Sub
Public Shared Sub GetAttribute(t As Type)
' Get instance of the attribute.
Dim MyAttribute As DeveloperAttribute =
CType(Attribute.GetCustomAttribute(t, GetType(DeveloperAttribute)), DeveloperAttribute)
If MyAttribute Is Nothing Then
Console.WriteLine("The attribute was not found.")
Else
' Get the Name value.
Console.WriteLine("The Name Attribute is: {0}.", MyAttribute.Name)
' Get the Level value.
Console.WriteLine("The Level Attribute is: {0}.", MyAttribute.Level)
' Get the Reviewed value.
Console.WriteLine("The Reviewed Attribute is: {0}.", MyAttribute.Reviewed)
End If
End Sub
End Class
Eksekusi program sebelumnya menampilkan teks berikut:
The Name Attribute is: Joan Smith.
The Level Attribute is: 42.
The Reviewed Attribute is: True.
Jika atribut tidak ditemukan, metode inisialisasi GetCustomAttribute
MyAttribute
ke nilai null. Contoh ini memeriksa instans MyAttribute
tersebut dan memberi tahu pengguna jika atribut tidak ditemukan. Jika DeveloperAttribute
tidak ditemukan di cakupan kelas, konsol akan menampilkan pesan berikut:
The attribute was not found.
Contoh sebelumnya mengasumsikan bahwa definisi atribut berada di namespace saat ini. Ingatlah untuk mengimpor namespace tempat definisi atribut berada jika tidak berada di namespace saat ini.
Mengambil Beberapa Instans dari Sebuah Atribut yang Diterapkan ke Cakupan yang Sama
Dalam contoh sebelumnya, kelas untuk diperiksa dan atribut tertentu yang akan ditemukan diteruskan ke GetCustomAttribute metode . Kode itu berfungsi dengan baik jika hanya satu instans atribut diterapkan pada tingkat kelas. Namun, jika beberapa instans atribut diterapkan pada tingkat kelas yang sama, GetCustomAttribute
metode tidak mengambil semua informasi. Dalam kasus di mana beberapa instans atribut yang sama diterapkan ke cakupan yang sama, Anda dapat menggunakan Attribute.GetCustomAttributes metode untuk menempatkan semua instans atribut ke dalam array. Misalnya, jika dua instans dari DeveloperAttribute
diterapkan pada tingkat kelas dari kelas yang sama, metode GetAttribute
dapat dimodifikasi untuk menampilkan informasi yang ditemukan di kedua atribut. Ingat, untuk menerapkan beberapa atribut pada tingkat yang sama. Atribut harus ditentukan dengan properti yang AllowMultiple
diatur ke true
di AttributeUsageAttribute kelas .
Contoh kode berikut menunjukkan cara menggunakan GetCustomAttributes
metode untuk membuat array yang mereferensikan semua instans DeveloperAttribute
di kelas tertentu. Kode kemudian menghasilkan nilai semua atribut ke konsol.
public:
static void GetAttribute(Type^ t)
{
array<DeveloperAttribute^>^ MyAttributes =
(array<DeveloperAttribute^>^) Attribute::GetCustomAttributes(t, DeveloperAttribute::typeid);
if (MyAttributes->Length == 0)
{
Console::WriteLine("The attribute was not found.");
}
else
{
for (int i = 0 ; i < MyAttributes->Length; i++)
{
// Get the Name value.
Console::WriteLine("The Name Attribute is: {0}." , MyAttributes[i]->Name);
// Get the Level value.
Console::WriteLine("The Level Attribute is: {0}." , MyAttributes[i]->Level);
// Get the Reviewed value.
Console::WriteLine("The Reviewed Attribute is: {0}.", MyAttributes[i]->Reviewed);
}
}
}
public static void GetAttribute(Type t)
{
DeveloperAttribute[] MyAttributes =
(DeveloperAttribute[]) Attribute.GetCustomAttributes(t, typeof (DeveloperAttribute));
if (MyAttributes.Length == 0)
{
Console.WriteLine("The attribute was not found.");
}
else
{
for (int i = 0 ; i < MyAttributes.Length ; i++)
{
// Get the Name value.
Console.WriteLine("The Name Attribute is: {0}." , MyAttributes[i].Name);
// Get the Level value.
Console.WriteLine("The Level Attribute is: {0}." , MyAttributes[i].Level);
// Get the Reviewed value.
Console.WriteLine("The Reviewed Attribute is: {0}.", MyAttributes[i].Reviewed);
}
}
}
Public Shared Sub GetAttribute(t As Type)
Dim MyAttributes() As DeveloperAttribute =
CType(Attribute.GetCustomAttributes(t, GetType(DeveloperAttribute)), DeveloperAttribute())
If MyAttributes.Length = 0 Then
Console.WriteLine("The attribute was not found.")
Else
For i As Integer = 0 To MyAttributes.Length - 1
' Get the Name value.
Console.WriteLine("The Name Attribute is: {0}.", MyAttributes(i).Name)
' Get the Level value.
Console.WriteLine("The Level Attribute is: {0}.", MyAttributes(i).Level)
' Get the Reviewed value.
Console.WriteLine("The Reviewed Attribute is: {0}.", MyAttributes(i).Reviewed)
Next i
End If
End Sub
Jika tidak ada atribut yang ditemukan, kode ini memberi tahu pengguna. Jika tidak, informasi yang terkandung dalam kedua instans dari DeveloperAttribute
ditampilkan.
Mengambil Beberapa Instans dari Sebuah Atribut yang Diterapkan ke Cakupan yang Berbeda
Metode GetCustomAttributes dan GetCustomAttribute tidak mencari seluruh kelas dan mengembalikan semua instans atribut di kelas tersebut. Sebaliknya, mereka hanya mencari satu metode atau anggota tertentu pada satu waktu. Jika Anda memiliki kelas dengan atribut yang sama yang diterapkan ke setiap anggota dan Anda ingin mengambil nilai di semua atribut yang diterapkan ke anggota tersebut, Anda harus menyediakan setiap metode atau anggota satu per satu ke GetCustomAttributes
dan GetCustomAttribute
.
Contoh kode berikut mengambil kelas sebagai parameter dan mencari DeveloperAttribute
(ditentukan sebelumnya) pada tingkat kelas dan pada setiap metode individual kelas tersebut:
public:
static void GetAttribute(Type^ t)
{
DeveloperAttribute^ att;
// Get the class-level attributes.
// Put the instance of the attribute on the class level in the att object.
att = (DeveloperAttribute^) Attribute::GetCustomAttribute (t, DeveloperAttribute::typeid);
if (att == nullptr)
{
Console::WriteLine("No attribute in class {0}.\n", t->ToString());
}
else
{
Console::WriteLine("The Name Attribute on the class level is: {0}.", att->Name);
Console::WriteLine("The Level Attribute on the class level is: {0}.", att->Level);
Console::WriteLine("The Reviewed Attribute on the class level is: {0}.\n", att->Reviewed);
}
// Get the method-level attributes.
// Get all methods in this class, and put them
// in an array of System.Reflection.MemberInfo objects.
array<MemberInfo^>^ MyMemberInfo = t->GetMethods();
// Loop through all methods in this class that are in the
// MyMemberInfo array.
for (int i = 0; i < MyMemberInfo->Length; i++)
{
att = (DeveloperAttribute^) Attribute::GetCustomAttribute(MyMemberInfo[i], DeveloperAttribute::typeid);
if (att == nullptr)
{
Console::WriteLine("No attribute in member function {0}.\n" , MyMemberInfo[i]->ToString());
}
else
{
Console::WriteLine("The Name Attribute for the {0} member is: {1}.",
MyMemberInfo[i]->ToString(), att->Name);
Console::WriteLine("The Level Attribute for the {0} member is: {1}.",
MyMemberInfo[i]->ToString(), att->Level);
Console::WriteLine("The Reviewed Attribute for the {0} member is: {1}.\n",
MyMemberInfo[i]->ToString(), att->Reviewed);
}
}
}
public static void GetAttribute(Type t)
{
DeveloperAttribute att;
// Get the class-level attributes.
// Put the instance of the attribute on the class level in the att object.
att = (DeveloperAttribute) Attribute.GetCustomAttribute (t, typeof (DeveloperAttribute));
if (att == null)
{
Console.WriteLine("No attribute in class {0}.\n", t.ToString());
}
else
{
Console.WriteLine("The Name Attribute on the class level is: {0}.", att.Name);
Console.WriteLine("The Level Attribute on the class level is: {0}.", att.Level);
Console.WriteLine("The Reviewed Attribute on the class level is: {0}.\n", att.Reviewed);
}
// Get the method-level attributes.
// Get all methods in this class, and put them
// in an array of System.Reflection.MemberInfo objects.
MemberInfo[] MyMemberInfo = t.GetMethods();
// Loop through all methods in this class that are in the
// MyMemberInfo array.
for (int i = 0; i < MyMemberInfo.Length; i++)
{
att = (DeveloperAttribute) Attribute.GetCustomAttribute(MyMemberInfo[i], typeof (DeveloperAttribute));
if (att == null)
{
Console.WriteLine("No attribute in member function {0}.\n" , MyMemberInfo[i].ToString());
}
else
{
Console.WriteLine("The Name Attribute for the {0} member is: {1}.",
MyMemberInfo[i].ToString(), att.Name);
Console.WriteLine("The Level Attribute for the {0} member is: {1}.",
MyMemberInfo[i].ToString(), att.Level);
Console.WriteLine("The Reviewed Attribute for the {0} member is: {1}.\n",
MyMemberInfo[i].ToString(), att.Reviewed);
}
}
}
Public Shared Sub GetAttribute(t As Type)
Dim att As DeveloperAttribute
' Get the class-level attributes.
' Put the instance of the attribute on the class level in the att object.
att = CType(Attribute.GetCustomAttribute(t, GetType(DeveloperAttribute)), DeveloperAttribute)
If att Is Nothing
Console.WriteLine("No attribute in class {0}.\n", t.ToString())
Else
Console.WriteLine("The Name Attribute on the class level is: {0}.", att.Name)
Console.WriteLine("The Level Attribute on the class level is: {0}.", att.Level)
Console.WriteLine("The Reviewed Attribute on the class level is: {0}.\n", att.Reviewed)
End If
' Get the method-level attributes.
' Get all methods in this class, and put them
' in an array of System.Reflection.MemberInfo objects.
Dim MyMemberInfo() As MemberInfo = t.GetMethods()
' Loop through all methods in this class that are in the
' MyMemberInfo array.
For i As Integer = 0 To MyMemberInfo.Length - 1
att = CType(Attribute.GetCustomAttribute(MyMemberInfo(i), _
GetType(DeveloperAttribute)), DeveloperAttribute)
If att Is Nothing Then
Console.WriteLine("No attribute in member function {0}.\n", MyMemberInfo(i).ToString())
Else
Console.WriteLine("The Name Attribute for the {0} member is: {1}.",
MyMemberInfo(i).ToString(), att.Name)
Console.WriteLine("The Level Attribute for the {0} member is: {1}.",
MyMemberInfo(i).ToString(), att.Level)
Console.WriteLine("The Reviewed Attribute for the {0} member is: {1}.\n",
MyMemberInfo(i).ToString(), att.Reviewed)
End If
Next
End Sub
Jika tidak ada instans DeveloperAttribute
yang ditemukan pada tingkat metode atau tingkat kelas, GetAttribute
metode memberi tahu pengguna bahwa tidak ada atribut yang ditemukan dan menampilkan nama metode atau kelas yang tidak berisi atribut . Jika atribut ditemukan, konsol Name
akan menampilkan bidang , Level
, dan Reviewed
.
Anda dapat menggunakan anggota kelas Type untuk mendapatkan metode dan anggota individual di kelas yang dilewatkan. Contoh ini pertama kali meminta Type
objek untuk mendapatkan informasi atribut untuk tingkat kelas. Selanjutnya, ia menggunakan Type.GetMethods untuk menempatkan instans semua metode ke dalam larik objek System.Reflection.MemberInfo untuk mengambil informasi atribut untuk tingkat metode. Anda juga dapat menggunakan metode Type.GetProperties untuk memeriksa atribut pada tingkat properti atau Type.GetConstructors untuk memeriksa atribut pada tingkat konstruktor.
Lihat juga
Saran dan Komentar
https://aka.ms/ContentUserFeedback.
Segera hadir: Sepanjang tahun 2024 kami akan menghentikan penggunaan GitHub Issues sebagai mekanisme umpan balik untuk konten dan menggantinya dengan sistem umpan balik baru. Untuk mengetahui informasi selengkapnya, lihat:Kirim dan lihat umpan balik untuk