将类型从视图MVC4传递到通用操作

本文关键字:操作 类型 视图 MVC4 | 更新日期: 2023-09-27 18:06:02

我正在做一些重构,我意识到我有一些严重重复的代码。旧代码:

public JsonResult GetResult(InheritType type)
{
    if(type == InheritType.TypeOne){
        var iqueryable = Session.Query<TypeOneInherit>()
        //34 lines of repeated code
    }else if(type == InheritType.TypeTwo){
        var iqueryable = Session.Query<TypeTwoInherit>()
        //34 lines of repeated code
    }else if(type == InheritType.TypeThree){
        var iqueryable = Session.Query<TypeThreeInherit>()
        //34 lines of repeated code
    }
}

我将其替换为以下内容:

public JsonResult GetResult(InheritType type){
    switch(type){
        case type.TypeOne:
            return GetResultGeneric<TypeOneInherit>
        case type.TypeTwo:
            return GetResultGeneric<TypeTwoInherit>
        case type.TypeThree:
            return GetResultGeneric<TypeThreeInherit>
    }
}
public JsonResult GetResultGeneric<T>(InheritType type) where T : Base
{
        var iqueryable = Session.Query<T>()
        //34 lines of non repeated code
}

我想做的是完全摆脱GetResult方法。现在我的动作看起来像这样:

@Url.Action("GetResult", "ResultController", new { type = InheritType.TypeOne })

动作在javascript中被设置为JQGrid的url。而不是传递枚举值,我希望能够只传递类型,这样我就可以绕过if块或switch语句。有什么办法可以做到吗?(我希望代码更简洁一点。当然,如果有更好的方法,我也会接受。另外,忽略我遗漏了很多返回的事实,它们应该隐含在注释中,我保证它们在我的工作代码中。)由于互联网。

将类型从视图MVC4传递到通用操作

你可以在MVC代码中创建一个SelectedType并将其作为对象发送,然后你可以像这样执行你的泛型方法:

public JsonResult GetResult(InheritType type){
    typeof(yourClass)
          .GetMethod("GetResultGeneric")
          .MakeGenericMethod(type.SelectedType.GetType())
          .Invoke(yourClass, new object[] {type});

}