mercredi 10 janvier 2018

Nested properties reflection C#

I need a method that returns a string representation based on a nested expression and i have some problems writing it. Let me explain this in code.

Let's say i have this object structure:

public class RandomClass
{
    public InnerRandomClass RandomProperty { get; set; }
}

public class InnerRandomClass
{
    public int SomeId { get; set; }
}

Then i have a method called Test. This method should be called like this an

var someString = Test(x => x.RandomProperty.SomeId);

And the expected return value in this case should be

Assert.AreEqual("RandomProperty.SomeId", someString);

I can write a method that returns "SomeId" but in my scenario i want the entire property structure, so i want "RandomProperty.SomeId".

I cant find anyone that wants to do something similar to this and i have inspected the Expression while debugging but cant find any information that helps.

I am aware that the solution might be pretty simple :D

Any suggestions on how the Test(Expression<Func<RandomClass, object>> expression) method should be implemented?

Thanks :)





Aucun commentaire:

Enregistrer un commentaire