[英]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.