简体   繁体   中英

Get full name properties from class in C#

i need to have this result :

ProgrammeEtude.Description

So, i have done something like that and it work

modelMember = $"{nameof(Gabarit.ProgrammeEtude)}.{nameof(Gabarit.ProgrammeEtude.Description)}";

But it's ugly and if we have more than one class to reach, it will not be clean. So, i would like to know if it's possible to create a function to get the fullName property without the first class clearly. Only by calling a function

// Like that
modelMember = typeof(ProgrammeEtude).GetPropertyFullName(nameof(ProgrammeEtude.Description));

// Or like that
modelMember = GetPropertyFullName(ProgrammeEtude.Description);

Thank you!

You can do it in runtime:

public class SomeClass
{
    public SomeClass Other;
}

public class Tests
{
    [Test]
    public void Test1()
    {
        var result = NameOf<SomeClass>(x => x.Other.Other.Other);
    }

    public static string NameOf<T>(Expression<Func<T,object>> selector)
    {
        const string joinWith = ".";
        return nameof(T) + joinWith + string.Join(joinWith, selector.ToString().Split('.').Skip(1));
    }
}

Result: SomeClass.Other.Other.Other

You can play with this function to get desired result - with/out namespaces/indexes/separation select just start or end or skip something, etc.

Be aware that this working great only if you don't use some funky variables/enums inside which accessed by dot. For more correct version you should traverse expression yourself, but in this example Im just kinda lazy to write this all, and better to use simple approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM