Can I get specific metadata from a Func?

前端 未结 4 571
逝去的感伤
逝去的感伤 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(Expression> 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;
    }
    

提交回复
热议问题