Attribute mittels Reflektion abfragen
Man kann mittels Reflektion unter anderem auch Attribute abfragen. Wie man das macht soll das kleine Beispiel mit C# und heute erstmals auch in Visual Basic zeigen:
Ich erstelle mir dazu erst einmal ein eigenes Attribut namens BlogAttribute, Basisklasse ist hier Attribute in System
C#
1 2 3 4 5 6 7 8 9 10 11 | public class BlogAttribute : System.Attribute { public BlogAttribute(string url, string name) { Name = name; Url = url; } public string Name { get; set; } public string Url { get; set; } } |
(VB)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | Public Class BlogAttribute Inherits System.Attribute Public Sub New(url__1 As String, name__2 As String) Name = name__2 Url = url__1 End Sub Public Property Name() As String Get Return m_Name End Get Set m_Name = Value End Set End Property Private m_Name As String Public Property Url() As String Get Return m_Url End Get Set m_Url = Value End Set End Property Private m_Url As String End Class |
Und dann setze ich das Attribut über der entsprechenden Klasse:
(C#)
1 2 3 | [Blog("http://wwww.biggle.de", "Biggle's Blog")] class MyClass {... } |
(VB)
1 2 3 | <Blog("http://wwww.biggle.de", "Biggle's Blog")> _ Class [MyClass] End Class |
Und nun werden wir das Attribut auslesen und das geht in etwa so:
(C#)
1 2 3 4 5 6 7 8 9 10 | var typeA = typeof(MyClass); var o = new List<object>(typeA.GetCustomAttributes(true)); o.ForEach(blog => { if (!(blog is BlogAttribute)) return; var u = (BlogAttribute)blog; Console.WriteLine(String.Format("Blog: {0} | Url: {1}", u.Name, u.Url)); }); |
(VB)
1 2 3 4 5 6 7 | Dim typeA As Type = GetType([MyClass]) For Each blog As BlogAttribute In (typeA.GetCustomAttributes(True)) If TypeOf blog Is BlogAttribute Then Console.WriteLine([String].Format("Blog: {0} | Url: {1}", blog.Name, blog.Url)) End If Next |
Viel Spass beim entwickeln : )