表达式解析 - 可以将属性名称数组作为字符串?

Bud*_*Joe 1 .net c# dsl expression expression-trees

有可能完成这个方法吗?是否可以在最新版本的C#中使用?将此视为DSL,以配置系统以查看某些对象上的某些属性更改.

List<string> list = GetProps<AccountOwner>(x => new object[] {x.AccountOwnerName, x.AccountOwnerNumber}); 
// would return "AccountOwnerName" and "AccountOwnerNumber"

public List<string> GetProps<T>(Expression<Func<T, object[]>> exp)
{  
    // code here
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

在C#6中,您将使用:

List<string> list = new List<string>
{
    nameof(AccountOwner.AccountOwnerName),
    nameof(AccountOwner.AccountOwnerNumber)
};
Run Code Online (Sandbox Code Playgroud)

在此之前,您当然可以将表达式树分开 - 最简单的解决方法可能是使用表达式树可视化工具,或者使用您已获得的代码并在方法中设置断点(只需返回它)现在为null)并检查调试器中的表达式树.我敢肯定它不会复杂 - 由于阵列的原因,比正常情况要多一些.

您可以使用匿名类型简化它,如果您使用:

List<string> list = Properties<AccountOwner>.GetNames(x => new {x.AccountOwnerName, x.AccountOwnerNumber});
Run Code Online (Sandbox Code Playgroud)

然后你可以:

public static class Properties<TSource>
{
    public static List<string> GetNames<TResult>(Func<TSource, TResult> ignored)
    {
        // Use normal reflection to get the properties
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你不关心订购,你可以使用

return typeof(TResult).GetProperties().Select(p => p.Name).ToList();
Run Code Online (Sandbox Code Playgroud)

如果你对订货照顾,你需要看看C#编译器给人以构造函数的参数,而不是名字-这是一个有点难看.请注意,我们不需要表达式树 - 我们只需要匿名类型的属性名称.(诚​​然,表达式树也可以正常工作.)