我可以得到特定的元数据从Func键&LT; T,对象&gt ;? [英] Can I get specific metadata from a Func<T, object>?
问题描述
考虑以下code:
string propertyName;
var dateList = new List<DateTime>() { DateTime.Now };
propertyName = dateList.GetPropertyName(dateTimeObject => dateTimeObject.Hour);
// I want the propertyName variable to now contain the string "Hour"
下面是扩展方法:
public static string GetPropertyName<T>(this IList<T> list, Func<T, object> func) {
//TODO: would like to dynamically determine which
// property is being used in the func function/lambda
}
有没有办法做到这一点?我想,也许这另一种方法,使用防爆pression&LT; Func键&LT; T,对象&gt;&GT;
而不是 Func键&LT; T,对象&gt;
会给我更多的力量找到我所需要的,但我很茫然如何。
Is there a way to do this? I thought that maybe this other method, using Expression<Func<T, object>>
instead of Func<T, object>
would give me more power to find what I need, but I am at a loss at how.
public static string GetPropertyName<T>(this IList<T> list, Expression<Func<T, object>> expr) {
// interrogate expr to get what I want, if possible
}
这是我第一次做这个事情深,LINQ的,所以也许我失去了一些东西明显。基本上我想传递lambda表达式的想法,让我得到编译时检查,但我不知道我的,我怎么能使用他们在这种特殊情况下的想法会工作。
This is the first time I have done anything this deep with Linq, so maybe I am missing something obvious. Basically I like the idea of passing in lambdas, so that I get compile-time checking, but I don't know that my idea on how I can use them in this particular case will work.
感谢
推荐答案
这是我使用的版本,它返回一个的PropertyInfo
,但得到这个名字实在是微不足道。
This is the version I use, it returns a PropertyInfo
, but getting the name is trivial.
public static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expression)
{
MemberExpression memberExpression = null;
if (expression.Body.NodeType == ExpressionType.Convert)
{
memberExpression = ((UnaryExpression) expression.Body).Operand as MemberExpression;
}
else if (expression.Body.NodeType == ExpressionType.MemberAccess)
{
memberExpression = expression.Body as MemberExpression;
}
if (memberExpression == null)
{
throw new ArgumentException("Not a member access", "expression");
}
return memberExpression.Member as PropertyInfo;
}
这篇关于我可以得到特定的元数据从Func键&LT; T,对象&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!