I'm looking for a way to get the interface member name of the expression passed into Client.SendMessage
. Below is what I've attempted, but I get an invalid cast exception.
public interface IFoo
{
void Operation1(object data);
void Operation2(object data);
}
public class FooClient<T>
{
public void SendMessage(Expression<Action<T>> expr)
{
// InvalidCastException:
// Cannot cast 'InstanceMethodCallExpressionN' to 'MemberExpression'
var iMemberName = ((MemberExpression)expr.Body).Member.Name;
Console.WriteLine(iMemberName);
}
}
class Program
{
static void Main()
{
var client = new FooClient<IFoo>();
// Should write 'Operation1'
client.SendMessage(x => x.Operation1("Hello, world!"));
// Should write 'Operation2'
client.SendMessage(x => x.Operation2("How are you?"));
}
}