获取表达式中成员的类型
我正在尝试学习表达式,但找不到如何获取表达式中属性的成员类型。例如,考虑这个方法:
static IEnumerable<Y> Filter<X,Y>(this IEnumerable<Person> p, Expression<Func<Person,X>> select, Expression<Func<X, Y>> format)
{
foreach (var item in p)
{
// member name
var m = ((MemberExpression)select.Body).Member;
// member attributes
var attributes = m.GetCustomAttributes(false);
// member type?
var a = select.Compile().Invoke(item);
var b = format.Compile().Invoke(a);
m.ToString();
yield return b;
}
}
它没有做任何有趣的事情,只是为了尝试。如果我这样做:
String y = _persons.Filter(p => p.DateOfBirth, d => d.ToString("yyyy")).ToArray().Single();
我可以在 Y 中获取该集合中人物的年份。我想知道“Filter”方法中“p.DateOfBirth”的类型。在不使用反射的情况下我该如何做到这一点?
问候。
I'm trying to learn expressions, and I cannot find how to get the member type of a property in a expression. For example, consider this method:
static IEnumerable<Y> Filter<X,Y>(this IEnumerable<Person> p, Expression<Func<Person,X>> select, Expression<Func<X, Y>> format)
{
foreach (var item in p)
{
// member name
var m = ((MemberExpression)select.Body).Member;
// member attributes
var attributes = m.GetCustomAttributes(false);
// member type?
var a = select.Compile().Invoke(item);
var b = format.Compile().Invoke(a);
m.ToString();
yield return b;
}
}
It doesn't do anything interesting, it is just for trying. If I do:
String y = _persons.Filter(p => p.DateOfBirth, d => d.ToString("yyyy")).ToArray().Single();
I can get in Y the year of the person in the collection. I want to know the type of "p.DateOfBirth" in the "Filter" method. How could I do that without using reflection?
Regards.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设我正确理解了您的意思,您只需要
Expression.Type
属性:Assuming I've understood you correctly, you just need the
Expression.Type
property: