考虑以下代码:
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 做这么深入的事情,所以我可能遗漏了一些明显的东西。基本上我喜欢传入 lambda 的想法,这样我就可以进行编译时检查,但我不知道我在这种特殊情况下如何使用它们的想法是否可行。
谢谢
最佳答案
这是我使用的版本,它返回一个 PropertyInfo
,但获取名称很简单。
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;
}
关于c# - 我可以从 Func<T, object> 获取特定的元数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/579963/