Lambda expression for cyclically intersecting class properties

If we say, I have the following classes:

Public Class Vehicle
        Sub New()
            Car = New Car()
            VehicleName = String.Empty
        End Sub

        Public Property Car As Car

        <Mask()>
        Public Property VehicleName As String
    End Class

    Public Class MaskAttribute
        Inherits Attribute

        Public Property Masking As String
    End Class

    <Serializable()>
     Public Class Car
        Sub New()
            CarName = String.Empty
        End Sub

        <Mask()>
        Public Property CarName As String
    End Class

The code examples above have the name of the custom Mask attribute.

Given that there is an object Dim v As new Vehicle()

How to get all the properties of this object that have their own mask attributes?

So, in this case, the expected loop through it: Properties: CarName and VehicleName, since both of them have a mask attribute

I understand that if I use reflection, performance will be slower than using a lambda expression. Please correct me if I am wrong.

Any idea to achieve this with lambda expression?

Thank!

+4
source share
1 answer

, Mask v (, ):

    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


, ( Access 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

, Name PropertyDescriptor props.


UPDATE

, , .

, :

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.

0

Source: https://habr.com/ru/post/1534948/


All Articles