Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Mengambil atribut kustom adalah proses sederhana. Pertama, deklarasikan instance atribut yang ingin Anda mengambil. 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 khusus pantulan, Anda harus menggunakan CustomAttributeData kelas , seperti yang ditunjukkan dalam Cara: Memuat Rakitan ke dalam Konteks Reflection-Only.
Bagian ini menjelaskan cara berikut untuk mengambil atribut:
Pemulihan beberapa instance atribut yang diterapkan pada lingkup yang sama
Mengambil beberapa instans atribut yang diterapkan ke cakupan yang berbeda
Mengambil Satu Instans Atribut
Dalam contoh berikut, DeveloperAttribute (dijelaskan di bagian sebelumnya) diterapkan ke kelas MainApp pada tingkat kelas. Metode GetAttribute menggunakan GetCustomAttribute untuk mengambil nilai yang disimpan di DeveloperAttribute pada tingkat kelas sebelum menampilkannya ke konsol.
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: {MyAttribute.Name}.");
// Get the Level value.
Console.WriteLine($"The Level Attribute is: {MyAttribute.Level}.");
// Get the Reviewed value.
Console.WriteLine($"The Reviewed Attribute is: {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 GetCustomAttribute menginisialisasi MyAttribute ke nilai null. Contoh ini memeriksa MyAttribute untuk instans 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 Atribut yang Diterapkan ke Cakupan yang Sama
Dalam contoh sebelumnya, kelas untuk diperiksa dan atribut tertentu yang akan ditemukan diteruskan ke metode GetCustomAttribute. Kode tersebut berfungsi dengan baik jika hanya satu instans atribut yang diterapkan pada tingkat kelas. Namun, jika beberapa instans atribut diterapkan pada tingkat kelas yang sama, metode GetCustomAttribute tidak mengambil semua informasi. Dalam kasus di mana beberapa instans atribut yang sama diterapkan ke cakupan yang sama, Anda dapat menggunakan metode Attribute.GetCustomAttributes untuk menempatkan semua instans atribut ke dalam array. Misalnya, jika dua instans DeveloperAttribute diterapkan pada tingkat kelas kelas yang sama, metode GetAttribute dapat dimodifikasi untuk menampilkan informasi yang ditemukan di kedua atribut. Untuk menerapkan beberapa atribut pada tingkat yang sama, atribut harus didefinisikan dengan properti AllowMultiple yang diatur ke true di kelas AttributeUsageAttribute.
Contoh kode berikut menunjukkan cara menggunakan metode GetCustomAttributes 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)
{
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: {MyAttributes[i].Name}.");
// Get the Level value.
Console.WriteLine($"The Level Attribute is: {MyAttributes[i].Level}.");
// Get the Reviewed value.
Console.WriteLine($"The Reviewed Attribute is: {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 akan memperingatkan pengguna. Jika tidak, informasi yang terkandung dalam kedua instans DeveloperAttribute ditampilkan.
Memperoleh Beberapa Instans 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 yang ditentukan 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 untuk GetCustomAttributes dan GetCustomAttribute.
Contoh kode berikut mengambil kelas sebagai parameter dan mencari DeveloperAttribute (ditentukan sebelumnya) pada tingkat kelas dan pada setiap metode individu dari 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, typeof (DeveloperAttribute));
if (att == null)
{
Console.WriteLine($"No attribute in class {t.ToString()}.\n");
}
else
{
Console.WriteLine($"The Name Attribute on the class level is: {att.Name}.");
Console.WriteLine($"The Level Attribute on the class level is: {att.Level}.");
Console.WriteLine($"The Reviewed Attribute on the class level is: {att.Reviewed}.\n");
}
// 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 {MyMemberInfo[i].ToString()}.\n");
}
else
{
Console.WriteLine($"The Name Attribute for the {MyMemberInfo[i].ToString()} member is: {att.Name}.");
Console.WriteLine($"The Level Attribute for the {MyMemberInfo[i].ToString()} member is: {att.Level}.");
Console.WriteLine($"The Reviewed Attribute for the {MyMemberInfo[i].ToString()} member is: {att.Reviewed}.\n");
}
}
}
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, metode GetAttribute memberi tahu pengguna bahwa tidak ada atribut yang ditemukan dan menampilkan nama metode atau kelas yang tidak berisi atribut . Jika atribut ditemukan, konsol akan menampilkan bidang Name, Level, dan Reviewed.
Anda dapat menggunakan anggota kelas Type untuk mendapatkan metode dan anggota individual di kelas yang dilewatkan. Contoh ini pertama kali meminta objek Type untuk mendapatkan informasi atribut untuk tingkat kelas. Selanjutnya, ini menggunakan Type.GetMethods untuk menempatkan instance dari semua metode ke dalam array objek System.Reflection.MemberInfo guna memperoleh informasi atribut pada tingkat metode. Anda juga dapat menggunakan metode Type.GetProperties untuk memeriksa atribut pada tingkat properti atau Type.GetConstructors untuk memeriksa atribut pada tingkat konstruktor.
Mengambil Kembali Atribut dari Anggota Kelas
Selain mengambil atribut di tingkat kelas, atribut juga dapat diterapkan ke masing-masing anggota seperti metode, properti, dan bidang. Metode GetCustomAttribute dan GetCustomAttributes dapat digunakan untuk mengambil atribut ini.
Contoh
Contoh berikut menunjukkan cara mengambil atribut yang diterapkan ke metode:
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Method)]
public class MyAttribute : Attribute
{
public string Description { get; }
public MyAttribute(string description) { Description = description; }
}
public class MyClass
{
[MyAttribute("This is a sample method.")]
public void MyMethod() { }
}
class AttributeRetrieval
{
public static void Main()
{
// Create an instance of MyClass
MyClass myClass = new MyClass();
// Retrieve the method information for MyMethod
MethodInfo methodInfo = typeof(MyClass).GetMethod("MyMethod");
MyAttribute attribute = (MyAttribute)Attribute.GetCustomAttribute(methodInfo, typeof(MyAttribute));
if (attribute != null)
{
// Print the description of the method attribute
Console.WriteLine($"Method Attribute: {attribute.Description}");
}
else
{
Console.WriteLine("Attribute not found.");
}
}
}