首页 > 解决方案 > C# Generic Type Inference...无论如何要自动推断数组元素的类型?

问题描述

我正在构建一个 MVC 核心 IHtmlHelper 扩展来处理表。粗略地说,您为扩展提供了一个 IEnumerable 数据记录列表和一个列布局,它会生成一个 HTML 表。

对于列布局,我希望某些方法是接受数据记录并从中返回值的 lambda。例如,对于表格的每一行,第一列应包含数据记录中的某某值。

所以 MVC IHtmlHelper 扩展方法看起来像:

namespace TableStuff
{
    public class Column<T>
    {
        public Func<T, string> TDContent { get; set; }
        // ... plus any other settings needed
    }

    public static class Table
    {
        public static IHtmlContent BasicTable<T>(
            this IHtmlHelper htmlHelper,
            IEnumerable<T> Data,
            IEnumerable<Column<T>> Columns
            )
        {
            return new HtmlString("just a mockup");
        }       
    }
}

要使用它,您:

public class Test
{
    class ListEntry
    {
        public string Id { get; set; }
    }

    public void DefineTable()
    {
        // fake a couple of things to make example minimal
        IHtmlHelper t = null;
        var Data = new List<ListEntry>();

        // generate the table; in reality this would be a razor page via @Html.BasicTable(...)
        var c = t.BasicTable(Data, new [] {
            new Column<ListEntry> { TDContent = i => i.Id }
        });
    }
}

我想知道为什么“new Column< ListEntry > { ... }”必须指定一个显式类型。我真的希望它只是“”new Column { ... }“并将类型推断为ListEntry。

标签: c#genericstype-inference

解决方案


推荐阅读