C#使用lambda表达式获取方法的参数名称

时间:2017-10-17 19:38:44

标签: c# lambda

是否可以以某种方式在方法对象上调用lambda表达式,以便您可以这样做..

(X => x.Property1)

然后应该返回PropertyInfo?

现在我有以下内容:

public static class MethodSupport<T>
{

   public static MethodInfo ActionInfo(Expression<Func<T, Action>> expression)
   {
       return MethodInfo<T>(expression);
   }

   public static MethodInfo MethodInfo<T>(LambdaExpression expression)
   {
        UnaryExpression unaryExpression = (UnaryExpression)expression.Body;
        MethodCallExpression methodCallExpression = (MethodCallExpression)unaryExpression.Operand;
        ConstantExpression methodCallObject = (ConstantExpression)methodCallExpression.Object;
        MethodInfo interfaceMethodInfo = (MethodInfo)methodCallObject.Value;

        Type implementedClassType = typeof(T);
        MethodInfo implementedMethodInfo = interfaceMethodInfo.GetImplementingMethod(implementedClassType);
        return implementedMethodInfo;
    }
}

这允许我返回MethodInfo,

MethodInfo m = MethodSupport<ImageGalleryController>.ActionInfo(c => c.AttachExisting);

但是我想要一些能让我返回给定属性的PropertyInfo

的东西

1 个答案:

答案 0 :(得分:0)

也许你需要这样的东西:

    public static PropertyInfo GetPropertyInfo<T>(Expression<Func<T>> propertyExpression)
    {
        return ((MemberExpression)propertyExpression.Body).Member as PropertyInfo;
    }