Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
Özel öznitelik almak basit bir işlemdir. İlk olarak, almak istediğiniz özniteliğin bir örneğini bildirin. Ardından, almak istediğiniz özniteliğin değeriyle yeni özniteliği başlatmak için Attribute.GetCustomAttribute yöntemini kullanın. Yeni öznitelik başlatıldıktan sonra, değerleri almak için özelliklerini kullanabilirsiniz.
Önemli
Bu makalede, yürütme bağlamı içine yüklenen kod için özniteliklerin nasıl alındığı açıklanmaktadır. Yalnızca yansıma bağlamı içine yüklenen kodun özniteliklerini almak için, CustomAttributeData bölümünde gösterildiği gibi sınıfını kullanmanız gerekir.
Bu bölümde, öznitelikleri almanın aşağıdaki yolları açıklanmaktadır:
Aynı kapsama uygulanan bir özniteliğin birden çok örneğini alma
Farklı kapsamlara uygulanan bir özniteliğin birden çok örneğini alma
Özniteliğin Tek Bir Örneğini Alma
Aşağıdaki örnekte, DeveloperAttribute (önceki bölümde açıklanmıştır) sınıf düzeyinde MainApp sınıfına uygulanır.
GetAttribute yöntemi, GetCustomAttribute kullanarak sınıf düzeyinde DeveloperAttribute depolanan değerleri konsolda görüntülemeden önce alır.
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
Önceki programın yürütülmesinde aşağıdaki metin görüntülenir:
The Name Attribute is: Joan Smith.
The Level Attribute is: 42.
The Reviewed Attribute is: True.
Öznitelik bulunamazsa, GetCustomAttribute yöntemi MyAttribute'i null bir değere başlatır. Bu örnek, böyle bir örneği MyAttribute denetler ve özniteliğin bulunup bulunmadığını kullanıcıya bildirir. sınıf kapsamında DeveloperAttribute bulunamazsa konsol aşağıdaki iletiyi görüntüler:
The attribute was not found.
Yukarıdaki örnekte öznitelik tanımının geçerli ad alanında olduğu varsayılır. Geçerli ad alanında değilse öznitelik tanımının bulunduğu ad alanını içeri aktarmayı unutmayın.
Aynı Kapsama Uygulanan Özniteliğin Birden Çok Örneğini Alma
Yukarıdaki örnekte, denetlenecek sınıf ve bulunacak belirli öznitelik GetCustomAttribute yöntemine geçirilir. Sınıf düzeyinde bir özniteliğin yalnızca bir örneği uygulandığında bu kod düzgün çalışır. Ancak, bir özniteliğin birden çok örneği aynı sınıf düzeyinde uygulanırsa, GetCustomAttribute yöntemi tüm bilgileri almaz. Aynı özniteliğin birden çok örneğinin aynı kapsama uygulandığı durumlarda, bir özniteliğin tüm örneklerini bir diziye yerleştirmek için Attribute.GetCustomAttributes yöntemini kullanabilirsiniz. Örneğin, aynı sınıfın sınıf düzeyinde iki DeveloperAttribute örneği uygulanırsa, GetAttribute yöntemi her iki öznitelikte bulunan bilgileri görüntülemek için değiştirilebilir. Aynı düzeyde birden çok öznitelik uygulamayı hatırlayın. özniteliği, AllowMultiple sınıfında true olarak ayarlanmış AttributeUsageAttribute özelliğiyle tanımlanmalıdır.
Aşağıdaki kod örneği, belirli bir sınıftaki tüm GetCustomAttributes örneklerine başvuran bir dizi oluşturmak için DeveloperAttribute yönteminin nasıl kullanılacağını gösterir. Kod daha sonra konsola tüm özniteliklerin değerlerini verir.
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
Öznitelik bulunmazsa, bu kod kullanıcıyı uyarır. Aksi takdirde, DeveloperAttribute her iki örneğinde de yer alan bilgiler görüntülenir.
Farklı Kapsamlara Uygulanan Bir Özniteliğin Birden Çok Örneğini Alma
GetCustomAttributes ve GetCustomAttribute yöntemleri, sınıfın tamamında arama yapıp bu sınıftaki bir özniteliğin tüm örneklerini döndürmez. Bunun yerine, aynı anda yalnızca bir belirtilen yöntemi veya üyeyi arar. Her üyeye aynı özniteliğin uygulandığı bir sınıfınız varsa ve bu üyelere uygulanan tüm özniteliklerdeki değerleri almak istiyorsanız, GetCustomAttributes ve GetCustomAttributeiçin her yöntemi veya üyeyi tek tek sağlamanız gerekir.
Aşağıdaki kod örneği bir sınıfı parametre olarak alır ve sınıf düzeyinde ve bu sınıfın her bir yönteminde DeveloperAttribute (daha önce tanımlanmıştır) arar:
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
Yöntem düzeyinde veya sınıf düzeyinde DeveloperAttribute örneği bulunamazsa, GetAttribute yöntemi kullanıcıya öznitelik bulunamadığını bildirir ve özniteliği içermeyen yöntemin veya sınıfın adını görüntüler. Bir öznitelik bulunursa, konsol Name, Levelve Reviewed alanlarını görüntüler.
Geçirilen sınıfa ait bireysel yöntemleri ve üyeleri almak için Type sınıfının üyelerini kullanabilirsiniz. Bu örnek, sınıf düzeyi için öznitelik bilgilerini almak için önce Type nesnesini sorgular. Daha sonra, yöntem düzeyi için öznitelik bilgilerini almak üzere tüm yöntemlerin örneklerini bir Type.GetMethods nesneleri dizisine yerleştirmek için System.Reflection.MemberInfo kullanır. Özellik düzeyinde öznitelikleri denetlemek için Type.GetProperties yöntemini veya oluşturucu düzeyinde öznitelikleri denetlemek için Type.GetConstructors de kullanabilirsiniz.
Sınıf Üyelerinden Öznitelikleri Alma
Öznitelikleri sınıf düzeyinde almaya ek olarak, öznitelikler yöntemler, özellikler ve alanlar gibi tek tek üyelere de uygulanabilir. bu öznitelikleri almak için GetCustomAttribute ve GetCustomAttributes yöntemleri kullanılabilir.
Örnek
Aşağıdaki örnekte bir yönteme uygulanan özniteliğin nasıl alınacağı gösterilmektedir:
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.");
}
}
}