gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:28:24 25 4
gpt4 key购买 nike

是否可以完成此方法?在最新版本的 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
}

最佳答案

在 C# 6 中,您将使用:

List<string> list = new List<string>
{
nameof(AccountOwner.AccountOwnerName),
nameof(AccountOwner.AccountOwnerNumber)
};

在此之前,您当然可以将表达式树分开 - 最简单的方法可能是使用表达式树可视化工具,或者使用您获得的代码并在方法中放置一个断点(只是让它暂时返回 null)并检查调试器中的表达式树。我敢肯定它不会非常复杂 - 只是比正常的多一点,因为阵列。

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

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

那么你可以:

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

如果你不关心顺序,你可以使用

return typeof(TResult).GetProperties().Select(p => p.Name).ToList();

如果您确实关心顺序,则需要查看 C# 编译器为构造函数参数提供的名称 - 这有点难看。请注意,尽管我们不需要表达式树——我们只需要来自匿名类型的属性名称。 (无可否认,表达式树同样有效。)

关于c# - 表达式解析 - 可以将属性名称数组作为字符串获取吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28330234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com