gpt4 book ai didi

VB.NET查找所有带有自定义标记的属性

转载 作者:行者123 更新时间:2023-12-02 19:41:47 24 4
gpt4 key购买 nike

有什么方法可以在属性/字段上创建自定义标记并在其上进行循环吗?像序列化器标记之类的东西。喜欢:

<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...

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

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

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

<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

最佳答案

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

关于VB.NET查找所有带有自定义标记的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20567177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com