I'm writing a dynamic model binder that binds functions to api calls.
This is my test controller with 2 functions. They have different functions with different parameter types.
public class MyTestController : System.Web.Mvc.Controller {
public ActionResult MyFunction() {
// Do awesome stuff
return result;
}
public ActionResult MyOtherFunction(int i) {
// Do other awesome stuff
return result;
}
}
With this model binder I want to to be able to select the specific functions and create my api call name.
public static class ModelBinder {
public static string GetApiCall<T>( Expression<Func<T, Func<ActionResult>>> expression ) {
var unaryExpression = (UnaryExpression)expression.Body;
var methodCallExpression = (MethodCallExpression)unaryExpression.Operand;
var methodInfoExpression = (ConstantExpression)methodCallExpression.Arguments.Last();
var methodInfo = (MemberInfo)methodInfoExpression.Value;
var controllerName = typeof( T ).Name.Replace( "Controller", "" );
var methodName = methodInfo.Name;
var myApiCallName = string.Format( "{0}_{1}", controllerName, methodName ).ToLower();
return myApiCallName;
}
}
Using the ModelBinder works with functions in the controller class without parameters. But not with the parameterized function.
var apiCallName1 = ModelBinder.GetApiCall<MyTestController>( x => x.MyFunction );
var apiCallName2 = ModelBinder.GetApiCall<MyTestController>( x => x.MyOtherFunction ); // Compiler Says no!
It's not possible to compile because the function definition does not match. In this case I would need to define another GetApiCall Method with another parameter type of Expression>>.
So here's the actual question:
Is there any type in C# that accepts all kinds of delegate types, but it bound to a specific return type? So only functions that return a results of type of ActionResult.
public static string GetApiCall<T>( Expression<Func<T, MagicDelegateTypeThatTakesAllFunctionsWithAllParameterTypes>> expression ) {
// do awesome stuff
}
Aucun commentaire:
Enregistrer un commentaire