Can I get specific metadata from a Func?

前端 未结 4 572
逝去的感伤
逝去的感伤 2021-02-04 17:16

Consider the following code:

string propertyName;
var dateList = new List() { DateTime.Now };
propertyName = dateList.GetPropertyName(dateTimeObj         


        
相关标签:
4条回答
  • 2021-02-04 17:49

    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;
    }
    
    0 讨论(0)
  • 2021-02-04 17:52

    Something like this should do the trick:

    public static string GetPropertyName<T>(this IList<T> list, Expression<Func<T, object>> expr) {
      MemberExpression member_expression = expr.Body as MemberExpression;
      if (member_expression == null)
          throw new ArgumentNullException("member_expression");
      MemberInfo member = member_expression.Member;
      PropertyInfo property = member as PropertyInfo;
      string proname = memeber.name;
    }
    

    WARNING: Air Code!

    0 讨论(0)
  • 2021-02-04 18:00

    here is a very easy and fast way to do it on this blog: http://blog.bittercoder.com/PermaLink,guid,206e64d1-29ae-4362-874b-83f5b103727f.aspx

    So given:

    Func func = Name => "Value";

    You can get the lambda parameter "Name" from the function delegate by calling:

    func.Method.GetParameters()[0].Name (would return "Name")

    Here's the revised Hash method from Andrey:

    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;
    }
    

    Hope it helps, Patrick

    0 讨论(0)
  • 2021-02-04 18:07

    Just a side note: func.Method.GetParameters()[0].Name is extremelly fast when compared with compiling the lambda and extracting the member expression, then the member info, then the name.

    0 讨论(0)
提交回复
热议问题