使用以下代码获取带有
v
对象(您在示例中使用的名称)的
Mask
属性的所有属性描述符列表:
Dim props As List(Of PropertyDescriptor) = (
From C As PropertyDescriptor In TypeDescriptor.GetProperties(v.GetType)
Where C.Attributes.OfType(Of MaskAttribute)().Count > 0
Select C
).ToList
你需要导入 System.ComponentModel
获取属性值
如果您需要获取属性的值,可以使用以下代码(在vb.net中使用属性名称访问属性):
Public Function GetPropertyValue(ByVal obj As Object, ByVal PropName As String) As Object
Dim objType As Type = obj.GetType()
Dim pInfo As System.Reflection.PropertyInfo = objType.GetProperty(PropName)
Dim PropValue As Object = pInfo.GetValue(obj, Reflection.BindingFlags.GetProperty, Nothing, Nothing, Nothing)
Return PropValue
End Function
请注意,在我们的示例中,属性的名称由列表props中每个 PropertyDescriptor 的属性Name给出。
更新
在您的示例中,这种方法不起作用,因为您在车辆类型的其他对象内部有一个汽车类型的对象,而我没有考虑内部对象。
我发现解决此问题的方法是使用递归:
Sub GetPropertiesWithMaskAttribute(Obj As Object, ByRef props As List(Of PropertyDescriptor))
Dim props1 As List(Of PropertyDescriptor) = (From C As PropertyDescriptor In TypeDescriptor.GetProperties(Obj) Select C).ToList
For Each prop In props1
If prop.Attributes.OfType(Of MaskAttribute)().Count > 0 Then
props.Add(prop)
Else
If prop.ComponentType.IsClass Then
GetPropertiesWithMaskAttribute(GetPropertyValue(Obj, prop.Name), props)
End If
End If
Next
End Sub
像这样调用:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim props As New List(Of PropertyDescriptor)
GetPropertiesWithMaskAttribute(v, props)
End Sub
然后,props
列表将包含所有带有 MaskAtribute
属性的属性。请注意,我使用了之前声明的子 GetPropertyValue
。