【发布时间】:2009-02-24 00:15:20
【问题描述】:
考虑以下代码:
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
}
有没有办法做到这一点?我想也许这种其他方法,使用Expression<Func<T, object>> 而不是Func<T, object> 可以让我更有能力找到我需要的东西,但我不知道怎么做。
public static string GetPropertyName<T>(this IList<T> list, Expression<Func<T, object>> expr) {
// interrogate expr to get what I want, if possible
}
这是我第一次用 Linq 做这么深的事情,所以也许我遗漏了一些明显的东西。基本上我喜欢传入 lambdas 的想法,这样我就可以进行编译时检查,但我不知道我在这种特殊情况下如何使用它们的想法是否可行。
谢谢
【问题讨论】:
标签: c# .net linq generics reflection