简体   繁体   English

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

[英]C# Use lambda expression to get parameter name of method

Is it possible to call a lambda expression on a method object in some way so that you can do this.. 是否可以通过某种方式在方法对象上调用lambda表达式,以便您可以执行此操作。

(x=>x.Property1) (x => x.Property1)

which then should return PropertyInfo? 然后应该返回PropertyInfo?

Right now I have the below: 现在我有以下内容:

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

Which allows me to return MethodInfo, 这使我可以返回MethodInfo,

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

but I want something else that will allow me to return PropertyInfo for a given property 但我想要其他一些东西可以让我返回给定属性的PropertyInfo

Maybe you need something like this: 也许您需要这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM