从映象(Reflection)类中读取属性信息

ZDNet软件频道 时间:2003-07-25 作者:ZDNet China |  我要评论()
本文关键词:vbtips
System.Reflection类提供了读取属性信息的功能。你可以使用映象类从类、方法中读取属性信息。使用映象类来读取属性信息使得在运行时间操作元数据变得非常灵活。
本文译自Builder.com,未经许可请勿转载System.Reflection类提供了读取属性信息的功能。你可以使用映象类从类、方法中读取属性信息。使用映象类来读取属性信息使得在运行时间操作元数据变得非常灵活。

以下类使用了一个固有属性(Serializable),以及一个通用的属性(Sample),代码段也包括了通用属性的定义:

<Serializable(), Sample("Attribute Sample")> _
Public Class TestClass

End Class

Public Class SampleAttribute
    Inherits System.Attribute

    Private attValue As String

    Public Sub New(ByVal Value As String)
        attributeValue = Value
    End Sub

    Public Property attributeValue()
        Get
            Return attValue
        End Get
        Set(ByVal Value)
            attValue = Value
        End Set
    End Property
End Class

为了确定一个类是否包含固有属性,可以使用类中的GetType方法。这将返回一个类型对象的引用。类型对象属性返回一个TypeAttributes对象,这一对象允许类之间的属性关联。以下代码说明了校验特定固有属性的过程:

Dim test As New TestClass()
Dim objectType As System.Type

objectType = test.GetType()
If (objectType.Attributes And _
        Reflection.TypeAttributes.Serializable) Then
    Debug.WriteLine("Serializable")
End If

If (objectType.Attributes And Reflection.TypeAttributes.Public) Then
    Debug.WriteLine("Public")
End If

If (objectType.Attributes And Reflection.TypeAttributes.Abstract) Then
    Debug.WriteLine("Abstract")
End If

为了校验通用属性,使用GetCustomAttributes方法。它将返回对象的数组,这些数组代表所有类中的属性。每一属性的类型都被校验以确定它是否是合法的,如果是,属性将被传递到属性类型的变量,并在需要的时候被处理:

Dim test As New TestClass()
Dim objectType As System.Type
Dim customAttribute As Object
Dim sampleAttr As SampleAttribute

objectType = test.GetType()
For Each customAttribute In objectType.GetCustomAttributes(False)
    If TypeOf (customAttribute) Is SampleAttribute Then
        sampleAttr = customAttribute
        Debug.WriteLine(sampleAttr.attributeValue)
    End If
Next



责任编辑:炒饭

欢迎评论或投稿


百度大联盟认证黄金会员Copyright© 1997- CNET Networks 版权所有。 ZDNet 是CNET Networks公司注册服务商标。
中华人民共和国电信与信息服务业务经营许可证编号:京ICP证010391号 京ICP备09041801号-159
京公网安备:1101082134