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
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
相关文章推荐
- [VB.NET]VB窗体可以增加自定义属性或方法吗?
- VB.NET 2003 Windows 应用全程自定义构建技术要点
- VB.NET自定义控件 —— 添加控件自定义属性
- 章鱼哥—VB.NET 控件中你不知道的属性之——AllowDrop 应用详解
- vb.net中用户自定义控件中属性、方法、事件的理解
- <VB.NET>自定义类创建属性
- vb.net 自定义常量在预处理指令的应用
- [VB.NET][问]如何让父窗体响应子窗体中的某一个自定义事件
- vb.net中自定义线帽
- 在VB.NET中应用SQLDMO
- vb.net中的操作符应用实例
- 使用QuickPart时应用自定义属性和Web Part Connection功能的演示视频
- OrFlying For VB.Net 在Asp.Net中的应用
- ASP.Net中自定义Http处理及应用
- 使用vb 6和vb.net为Office应用添加工具栏和按钮
- ASP.Net中自定义Http处理及应用之HttpHandler篇(转自:http://7880.com/Info/Article-2b783c20.html)
- vb.net中的自定义事件
- 开发应用时如何利用C#自定义属性
- ASP.Net中自定义Http处理及应用之HttpModule篇
- ASP.Net访问母版页(MasterPage)控件、属性、方法及母版页中调用内容页,获取用户自定义控件里面的子控件的方法