我正在尝试从应用于属性的自定义属性访问数据,我只是一直没有返回任何内容。这是我最近的尝试。
属性:
<AttributeUsage(AttributeTargets.Property)>
Public Class TestAttribute
Inherits System.Attribute
Public Property name As String
Sub New(ByVal dirName As String)
name = dirName
End Sub
End Class
财产:
<Test("My Awesome Attribute")>
Public Property testProperty As String
电话:
testProperty = "Blah Blah"
Try
Dim attr As System.Attribute = Attribute.GetCustomAttribute(testProperty.GetType(), GetType(TestAttribute))
Dim testAttr As TestAttribute = CType(attr, TestAttribute)
Console.WriteLine(testAttr.name)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
答案 0 :(得分:0)
感谢Same Axe,我被带到了一个我从未见过的页面,并帮助我弄清楚我做错了什么。我曾尝试过GetProperty路线,但显然是错误的。我现在正在使用它。
属性:
<AttributeUsage(AttributeTargets.Property)>
Public Class TestAttribute
Inherits System.Attribute
Public Property name As String
Sub New(ByVal dirName As String)
name = dirName
End Sub
End Class
财产:
<Test("My Awesome Attribute")>
Public Property testProperty As String
电话:
testProperty = "Blah Blah"
Try
Dim pinfo As PropertyInfo = Me.GetType().GetProperty("testProperty")
Dim attr As System.Attribute = Attribute.GetCustomAttribute(pinfo, GetType(TestAttribute))
Dim testAttr As TestAttribute = CType(attr, TestAttribute)
Console.WriteLine(testAttr.name)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
输出:
My Awesome Attribute