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

Jas*_*ing 7 .net c# 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"
Run Code Online (Sandbox Code Playgroud)

这是扩展方法:

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
}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?我想也许这个其他的方法,使用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
}
Run Code Online (Sandbox Code Playgroud)

这是我第一次与Linq做了很多深入的事情,所以也许我错过了一些明显的东西.基本上我喜欢传入lambdas的想法,所以我得到了编译时检查,但我不知道我在这种特殊情况下如何使用它们的想法是可行的.

谢谢

gco*_*res 12

这是我使用的版本,它返回一个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;
}
Run Code Online (Sandbox Code Playgroud)


Pat*_*olf 6

在这个博客上,这是一个非常简单快捷的方法:http://blog.bittercoder.com/PermaLink,guid,206e64d1-29ae-4362-874b-83f5b103727f.aspx

所以给出:

Func func = Name =>"Value";

您可以通过调用以下函数从函数委托中获取lambda参数"Name":

func.Method.GetParameters()[0] .Name(将返回"Name")

这是Andrey的修改后的Hash方法:

public Dictionary<string, T> Hash<T>(params Func<string, T>[] args)
where T : class
{
    var items = new Dictionary<string, T>();
    foreach (var func in args)
    {
        var item = func(null);
        items.Add(func.Method.GetParameters()[0].Name, item);
    }
    return items;
}
Run Code Online (Sandbox Code Playgroud)

帕特里克希望它有所帮助