[英]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.
所以,我想知道是否有可能创建一个函数来在没有第一类的情况下获取 fullName 属性。 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结果: 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.
对于更正确的版本,你应该自己遍历表达式,但在这个例子中,我有点懒惰写这一切,最好使用简单的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.