您的位置:首页 > 编程语言 > VB

vb.net中自定义属性的应用

2008-08-20 23:22 447 查看
给类或字段加上自定义属性有时候是非常有用的,我亲身试了试:

1.定义属性类:

<AttributeUsage(AttributeTargets.Field)> _

Public Class FieldAttribute

Inherits Attribute

Private mNum As Integer

Private mName As String

Public ReadOnly Property Num() As Integer

Get

Return mNum

End Get

End Property

Public ReadOnly Property Name() As String

Get

Return mName

End Get

End Property

Public Sub New(ByVal name As String, ByVal num As Integer)

mNum = num

mName = name

End Sub

End Class

2.获得属性值:


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim c1 As New Class1

Dim myType As Type = c1.GetType

'Dim ob As Object() = myType.GetCustomAttributes(GetType(layoutAttribute), False)

'For Each layout As layoutAttribute In ob

' MessageBox.Show(layout.Name)

'Next

Dim memberinfos() As MemberInfo = myType.GetMembers(BindingFlags.Public Or BindingFlags.Instance)

Dim arrList As New List(Of FieldAttribute)

For Each mem As MemberInfo In memberinfos

Dim ob As Object() = mem.GetCustomAttributes(GetType(FieldAttribute), False)

If ob IsNot Nothing AndAlso ob.Length > 0 Then

arrList.Add(ob(0))

End If

Next

End Sub
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: