c# - 如何将参数传递给 MVC 中的 GenericController 构造函数?

标签 c# asp.net-mvc generics

我有一个具有以下方法的 GenericController:

public class GenericGridController<T, TKey>:Controller
    where T : class
    where TKey : IComparable
{
    string GetFilterParam();
    string GetGridPartialName();
    List<T> GetGridModel(TKey param);
    List<T> GetGridModel(T entity);
    ActionResult GetGrid(TKey param);
    ActionResult Add(T entity);
    ActionResult Edit(T entity);
    ActionResult Delete(T entity);
}

当我需要创建一个网格时,我正在创建一个新的 Controller ,它继承自 GenericGridController,我需要覆盖 GetFilterParam 和 GetGridParialName,以提供特定的名称。

这工作得很好。现在我不想重写这两种方法,并且:

我试图做“我不明白的事情”: - 我在通用 Controller 中制作了 2 个字符串属性 - 我从构造函数中初始化它们,类似于:

    public string FilterParam { get; set; }
    public string GridPartialName { get; set; }

    public GenericGridController(string filterParamName, string partialName)
    {
        FilterParam = filterParamName;
        GridPartialName = partialName;
    }

然后我创建了一个新的 TestController,继承自 GenerigGridController,我看到他要求实现缺少的构造函数,如下所示:

public class TestController : GenericGridController<Candidat,int>
    {
        public TestController(string filterParamName, string partialName)
            : base(filterParamName, partialName)
        {

        }        
    }

我期待做这样的事情:

 public class TestController : GenericGridController<Candidat,int>("param","PartialView"){}

我的问题是:如何在 GenericGridController 构造函数中提供需要它的 2 个参数。

也许这是一个愚蠢的问题,我只是想了解它是如何工作的。

最佳答案

您不能将参数 作为类声明的一部分。

我想到了两个解决方案:

  1. 使用具有默认值的属性并在派生类中覆盖 公共(public)字符串 FilterParam { 得到;放; } 公共(public)字符串 GridPartialName { 得到;放; }

    公共(public) GenericGridController() { this.FilterParam = "defaultFilterParamValue"; this.GridPartialName = "defaultGridPartialNameValue"; }

在派生类中

public DerivedGridController()
{
    this.FilterParam = "foo";
    this.GridPartialName = "derived";
}
  1. 将这些属性声明为抽象

公共(public)抽象字符串 FilterParam { 得到; } 公共(public)抽象字符串 GridPartialName { 得到; } 使用 abstract 强制每个派生类实现那些返回常量或计算值的属性

public override string FilterParam { get { return "myFilterParam"; } }

关于c# - 如何将参数传递给 MVC 中的 GenericController 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36141333/

相关文章:

c# - 无需枚举即可备份大量文件

c# - 通用方法与强制转换

asp.net-mvc - ASP.NET MVC - 将 Json 结果与 ViewResult 结合起来

Java 泛型 - 子类型检查?

c# - 类似命名方法的.NET 扩展方法冲突解决?

c# - DropDownList 未在 ASP.NET MVC 中填充正确的值

ASP.Net MVC 使用特定布局页面返回同一 View

javascript - jQuery 函数每 10 秒从客户端调用 Controller 方法 mvc razor

Java 泛型、对象和通配符的区别和说明

python - Generic[T] 基类 - 如何从实例中获取 T 的类型?