Choosing a class method name using a Lambda expression

Currently, there is a method in my code:

.AddMethod(nameof(IRoleService.GetRoles))

What I'm trying to do is select an interface method using a lambda expression and then get the method name inside AddMethod. Thus, the result will be:

.AddMethod<IRoleService>(x=> x.GetRoles)

I tried this:

AddMethod<T>(Expression<Func<T, Action>> expression);

But the problem is that some of the interface methods have input parameters that I try to ignore, because I just need the method name. I would be grateful if you would help me with this.

Alex

+4
source share
2 answers

This can be achieved with a little jerk in the LambdaExpressionfollowing way:

string GetMethodCallName(LambdaExpression expression)
{
    var unary = (UnaryExpression)expression.Body;
    var methodCall = (MethodCallExpression)unary.Operand;
    var constant = (ConstantExpression)methodCall.Object;
    var memberInfo = (MemberInfo)constant.Value;

    return memberInfo.Name;
}

, GetMethodCallName x => x.GetRoles, , , x. , AddMethod , Action, Func:

void AddMethod<T>(Expression<Func<T, Action>> expression);
void AddMethod<T, Arg1>(Expression<Func<T, Action<Arg1>>> expression);
void AddMethod<T, Arg1, Arg2>(Expression<Func<T, Action<Arg1, Arg2>>> expression);

void AddMethod<T, TResult>(Expression<Func<T, Func<TResult>>> expression);
void AddMethod<T, Arg1, TResult>(Expression<Func<T, Func<Arg1, TResult>>> expression);
void AddMethod<T, Arg1, Arg2, TResult>(Expression<Func<T, Func<Arg1, Arg2, TResult>>> expression);

AddMethod GetMethodCallName :

void AddMethod<T, Arg1>(Expression<Func<T, Action<Arg1>>> expression)
{
    var methodName = GetMethodCallName(expression);
}

AddMethod :

.AddMethod<IRoleService>(x => x.GetRoles);
.AddMethod<IRoleService, TResult>(x => x.GetRoles);
.AddMethod<IRoleService, Arg1, TResult>(x => x.GetRoles);

:

  • TResult - .GetRoles
  • Arg1 - .GetRoles
0

,

, .

, , , , . :

// I don't know which parameters accept your methods...
AddMethod<IRoleService>(x => x.GetRoles("arg1", 2));

OP ...

, , ?

. (.. , ).

, ? , ? #? : .

+3

All Articles