mardi 23 août 2022

C# reflection get all properties inside the proerperties with custom attribute

I am writing a method for extracting all properties from an object (including properties of its own) with custom attribute . For example

  public class SomeModel
{

    [Custom]
    public string Name { get; set; }


    public string TestData { get; set; }

    [Custom]
    public string Surname { get; set; }

   public  InnerModel InnerModel { get; set; }
}

And Inner Model :

  public class InnerModel
{
    public string Id { get; set; } = "TestID";

    [Custom]
    public string Year { get; set; }

    public ThirdObject HidedObject { get; set; }
}

And the third one :

 public class ThirdObject
{
    [Custom]
    public string  HidedName { get; set; }
}

I need to find all properties with "Custom" attribute . Testing :

SomeModel model = new SomeModel()
        {
            Name = "farid",
            Surname = "Ismayilzada",
            TestData = "Test" ,
            InnerModel = new InnerModel() { Year ="2022" , HidedObject= New ThirdObject{ HidedName="Secret"}}
        };

I need to write the method

GetMyProperties(model) => List<PropInf>()
[PropertyName= Name,Value=Farid ,Route="Name" ]
[PropertyName= Surname,Value=Ismayilzada,Route="Surname" ]
[PropertyName= Year,Value=2022,Route="InnerModel.Year" ]
[PropertyName= HidedName,Value=Secret,Route="InnerModel.HidedObject.HidedName" ]

How to get this information ?





Aucun commentaire:

Enregistrer un commentaire