【发布时间】:2021-06-07 10:09:03
【问题描述】:
我有一堂课:
public class Student
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("age")]
public int Age { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
}
我有一个方法:
public static List<string> PrintPropertyNames<T>(params Expression<Func<T, object>>[] properties)
{
var list = new List<string>();
foreach (var p in properties)
{
if (p.Body is MemberExpression)
{
var e = (MemberExpression)p.Body;
list.Add(((JsonPropertyAttribute)e.Member.GetCustomAttribute(typeof(JsonPropertyAttribute))).PropertyName);
}
else
{
var e = (MemberExpression)((UnaryExpression)p.Body).Operand;
list.Add(((JsonPropertyAttribute)e.Member.GetCustomAttribute(typeof(JsonPropertyAttribute))).PropertyName);
}
}
return list;
}
我这样称呼:
Console.WriteLine(string.Join(" ", PrintPropertyNames<Student>(x => x.Age, x => x.Country)));
现在,我想修改我的方法定义以只接受一个参数,但我不知道该怎么做。
我试着做这样的事情:
public static List<string> PrintPropertyNames2<T>(Expression<Func<T, object>>[] properties)
我这样称呼:
Console.WriteLine(string.Join(" ", PrintPropertyNames2<Student>(new Expression<Func<Student, object>>[] { x => x.Age, x => x.Country })));
我尝试将其简化为:
Console.WriteLine(string.Join(" ", PrintPropertyNames2<Student>(new [] { x => x.Age, x => x.Country })));
但是编译器找不到最合适的类型。所以我必须明确地编写类型,它看起来很丑,而且不是我真正想要的。我需要它通用的。
我想在最终版本中做的事情如下:
Console.WriteLine(string.Join(" ", PrintPropertyNames<Student>(x => x.Age && x.Country && x.Name)));(输出应该是-age country name)
我不确定这是否可能,但我想将我的所有属性放在一个表达式中并立即获取它们的 json 属性值。
【问题讨论】:
-
请注意,
x => x.Age && x.Country && x.Name不是可以编译的有效表达式——Age是int,Name是string,您不能将它们与&&
标签: c# lambda reflection expression expression-trees