簡體   English   中英

C#使用lambda表達式獲取方法的參數名稱

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

是否可以通過某種方式在方法對象上調用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

也許您需要這樣的東西:

    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