将泛型类型列表传递给方法

Passing list of generic types into method

我有一个在 MVC 项目中动态构造 html table 的方法。此 table 可以显示四种实体类型之一的集合。我需要做的是将实体类型传递到方法中,而无需为每种类型编写方法。

这是我的方法声明:

public static HtmlString Table(int rows, int columns, string[] headers, List<MyInterface> model)
{
    //...
}

这是我的观点以及我如何调用我的辅助方法:

@model List<MyModel>

<some html>

@OfficeUiHelper.Table(Model.Count, 5, new string[] { "First Name", "Last Name", "Username", "Company", "Role" }, Model)

这是我的界面:

public interface MyInterface
{
}

这是我的实体类型之一:

public partial class MyModel : MyInterface
{
    // Properties
}

总之,当我这样做时,我得到一个错误:

Cannot convert from "System.Collections.Generic.List<MyModel>" to "System.Collections.Generic.List<MyInterface>".

您可以添加一个所有四个 class 都实现的接口,然后您可以传递该接口的列表而不是 object 类型的列表。这使您免于许多演员表。

public partial class MyModel : MyInterface
{
    // Properties
}

interface MyInterface {}

public static HtmlString Table(int rows, int columns, string[] headers, List<MyInterface> model)

根本不需要泛型。此外,泛型意味着可以传递共享条件的所有类型,而不仅仅是少数。那么当您的方法的用户传递 YourModel-class 而不是 MyMopdel 时会发生什么。