c# - 我可以从 Func<T, object> 获取特定的元数据吗?

标签 c# .net linq generics reflection

考虑以下代码:

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/

相关文章:

c# - 连接池

c# - 处理连接/查询的最佳实践

c# - Crystal 报表模板?

c# - Linq 通过层次结构递归

C#:按可为空的 DateTime 属性对对象列表进行排序

c# - 使用 .net 的 Telnet 连接

c# Windows 窗体应用程序在错误后使进程继续运行

c# - as和cast的比较

.net - 使用 .NET 优化蚁群

c# - 如何更新 ObservableCollection 类中的单个项目?