VB.NET使用custon标记查找所有属性

时间:2013-12-13 12:59:51

标签: vb.net reflection

有什么方法可以在属性/字段上创建一个custon标记并对其进行循环?比如序列化器标记。 像:

<Property marker for X>
Public Propetry A as Something...

<Property marker for X>
Public Propetry B as Something...

<Property marker for X>
Public Propetry C as Something...

<Property marker for X>
Public Propetry D as Something...

<Property marker for Y>
Public Propetry W as Something...

<Property marker for Y>
Public Propetry X as Something...

然后在特定属性标记上创建一个loop ...

For Each MarkX as Something in Class.GetAllPropertyWithXMarker
    'todo...
next

--- 感谢repply,这是我如何使用它的一个非常简单的例子。当然这只是一个例子,但对我来说是完美的。 -

<AttributeUsage(AttributeTargets.Field)>
Public Class FieldAtribute
    Inherits Attribute

    Public Skip As Boolean = False

    Public Sub New(Skip As Boolean)
        Me.Skip = Skip
    End Sub

End Class

Public Class Teste1

    <FieldAtribute(True)> _
    Public A As String = "A" 'Skip

    <FieldAtribute(False)> _
    Public B As String = "B" 'Enable

    <FieldAtribute(False)> _
    Public C As String = "C" 'Enable

End Class

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim Test As New Teste1
    With Test
        .A = True
        .B = True
        .C = True
    End With

    ShowValues(Test)
    Test = DefaultValues(Test)
    ShowValues(Test)
End Sub

Private Function DefaultValues(T As Teste1) As Teste1
    For Each Info As System.Reflection.FieldInfo In T.GetType.GetFields
        Dim CustonData As FieldAtribute = Info.GetCustomAttributes(GetType(FieldAtribute), False)(0)
        If (Not CustonData.Skip) Then
            CallByName(T, Info.Name, CallType.Set, {False})
        End If
    Next

    Return T
End Function

Private Sub ShowValues(T As Teste1)
    Console.WriteLine(T.A)
    Console.WriteLine(T.B)
    Console.WriteLine(T.C)
End Sub

输出:

True
True
True

True <-- Target skiped by custon marker.
False
False

2 个答案:

答案 0 :(得分:3)

您可以创建自定义属性并使用它标记相关属性。通过使用反射,您可以获取类型的属性,过滤使用属性标记的属性并处理它们 请参阅以下文档:

答案 1 :(得分:2)

Public Class PropertyMarker
    Inherits System.Attribute
End Class

Public Class Class1
    <PropertyMarker()> _
    Public ReadOnly Property A() As String
        Get
            Return "A"
        End Get
    End Property

    <PropertyMarker()> _
    Public ReadOnly Property B() As String
        Get
            Return "B"
        End Get
    End Property

    Public ReadOnly Property C() As String
        Get
            Return "C"
        End Get
    End Property
End Class

Sub Main()
    For Each p In (From pp In GetType(Class1).GetProperties() Where pp.GetCustomAttributes(GetType(PropertyMarker), False).Any Select pp)
        Console.WriteLine(p.Name)
    Next

    Console.ReadLine()
End Sub
相关问题