如何:检索自定义属性

更新:2007 年 11 月

您可以使用 Attribute 类的 GetCustomAttributeGetCustomAttributes 方法检索自定义属性。

从类检索自定义属性的单个实例

  1. 将 Imports 语句添加到源代码的开头,以便从 System 命名空间导入 Attribute 类:

    Imports System.Attribute
    
  2. 创建一个过程来检索属性

    Sub RetrieveAttribute()
    
    End Sub
    
  3. 在此过程中,声明一个 Attribute 类型的变量,并声明另一个与您要检索的属性类型相同的变量:

    Dim Attr As Attribute
    Dim CustAttr As CustomAttribute
    
  4. 使用 GetType 运算符将类类型和属性类型传递给 GetCustomAttribute 方法调用,然后将返回的值赋给声明为 Attribute 的变量:

    Attr = GetCustomAttribute(Me.GetType, _
                              GetType(CustomAttribute), False)
    
  5. 使用 CType 函数将属性的数据类型从泛型属性类型转换为您检索的特定属性类型。然后将结果分配给声明为自定义属性类型的变量:

    CustAttr = CType(Attr, CustomAttribute)
    
  6. 检查是否已检索属性,如果是,请使用该属性的字段、属性和方法:

    If CustAttr Is Nothing Then
        MsgBox("The attribute was not found.")
    Else
        'Get the label and value from the custom attribute.
        MsgBox("The attribute label is: " & CustAttr.Label)
        MsgBox("The attribute value is: " & CustAttr.Value)
    End If
    

    在以上示例中,RetrieveAttribute 过程调用 System.Attribute 类的 GetCustomAttribute 方法以将自定义属性应用于 ThisClass 类。GetCustomAttribute 是一个共享方法,因此您不必先创建 System.Attribute 的实例。CType 函数将返回的属性从 System.Attribute 类型转换为 CustomAttribute 自定义属性类型。

请参见

任务

如何:定义自己的属性

概念

属性的应用

检索存储在属性中的信息

参考

GetCustomAttribute

GetCustomAttributes

GetType 运算符

CType 函数

IsNothing 函数

GetAttr 函数

AttributeUsageAttribute