Created
January 27, 2015 11:07
-
-
Save geirsagberg/66284a7e6083d72de64c to your computer and use it in GitHub Desktop.
MvvmCross MethodBinding extensions for fluent syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class MethodBindingExtensions | |
{ | |
public static MvxFluentBindingDescription<TTarget, TSource> ToMethod<TTarget, TSource>(this MvxFluentBindingDescription<TTarget, TSource> description, Expression<Func<TSource, Action>> method) where TTarget : class | |
{ | |
var name = FindMethodName(method); | |
return description.To(name); | |
} | |
public static MvxFluentBindingDescription<TTarget, TSource> ToMethod<TTarget, TSource>(this MvxFluentBindingDescription<TTarget, TSource> description, Expression<Func<TSource, Func<Task>>> method) where TTarget : class | |
{ | |
var name = FindMethodName(method); | |
return description.To(name); | |
} | |
private static string FindMethodName(LambdaExpression method) | |
{ | |
var body = method.Body as UnaryExpression; | |
if (body == null) | |
throw new ArgumentException("Method body must be UnaryExpression"); | |
var operand = body.Operand as MethodCallExpression; | |
if (operand == null) | |
throw new ArgumentException("Method body's operand must be MethodCallExpression"); | |
if (operand.Arguments.Count < 3) | |
throw new ArgumentException("Method body's operand should have 3 arguments"); | |
var argument = operand.Arguments[2] as ConstantExpression; | |
if (argument == null) | |
throw new ArgumentException("Method body's operand's third argument should be ConstantExpression"); | |
var methodInfo = argument.Value as MethodInfo; | |
if (methodInfo == null) | |
throw new ArgumentException("Method body's operand's third argument should have a MethodInfo as Value"); | |
var name = methodInfo.Name; | |
return name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment