如何在类构造函数参数

时间:2015-12-26 00:46:44

标签: c# asp.net-mvc

我试图在我的MVC控制器中导出一些代码(导出到Excel)更通用,因为我已经达到了在多个控制器中输入几乎完全相同的代码的程度。为了使导出到Excel功能只存在于一个地方 - 而不是在很多地方 - 我有了使用通用IEnumerable的想法,所以我可以将任何 IEnumerable提供给类。 (见下面的代码块。)

我知道我可以使用byte []作为参数(我可能仍然使用它作为其他构造函数选择),但如果我可以在这个实例中使用IEnumerable,那将会很好。

然而,Intellisense立即告诉我"无法找到类型或命名空间T"。

是否可以将IEnumerable<T>用于此目的?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.CentralFunctions
{
    public class ExportToExcel
    {
        ExportToExcel(IEnumerable<T> inputCollection)
        {
            // TODO: place my "export to excel" commands here.
        }
    }
}

4 个答案:

答案 0 :(得分:1)

T类型为“未知”,即未指定。

您似乎想要制作ExportToExcelgeneric,而T似乎是一个类型参数:

public class ExportToExcel<T>
{
    ExportToExcel(IEnumerable<T> inputCollection)
    {
        // ...
    }
}

答案 1 :(得分:1)

您需要在类级别声明T类型,如果需要,还可以向T添加约束

public class ExportToExcel<T>
{
    ExportToExcel(IEnumerable<T> inputCollection)
    {
        // TODO: place my "export to excel" commands here.
    }
}

答案 2 :(得分:1)

您需要在某处定义T代表编译器的内容。由于您正在处理类构造函数,因此需要使类成为通用的,以便定义T

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.CentralFunctions
{
    public class ExportToExcel<T>
    {
        ExportToExcel(IEnumerable<T> inputCollection)
        {
            // TODO: place my "export to excel" commands here.
        }
    }
}

答案 3 :(得分:0)

我已经接受@ NightOwl888作为最佳答案。感谢@Sergei和@Luke的回答。

他们的回答帮助我正确编写了类构造函数,现在我可以大大简化代码。我正在分享这个,因为它解释了问题的完整背景,并演示了如何将它放入我的MVC系统。这是&#34;你好世界&#34;版本,可以帮助像我这样的人,帮助他们了解如何开始。

现在我可以将控制器操作简化为:

查看:

<p>@Html.ActionLink("Export to Excel","ExportToExcel")</p>

控制器操作:

public ActionResult ExportToExcel()
{
    IEnumerable<TroveLog> data = db.TroveLogs.AsEnumerable();
    var export = new ExportToExcel<TroveLog>(data);

    return RedirectToAction("Index");
}

这是我可以放置单个代码块的地方,可以将任何 IEnumerable导出到Excel。当我使用调试模式(F5)时,我可以看到Debug.WriteLine结果并验证我是否看到了正确的信息。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;

namespace WebApplication1.CentralFunctions
{
    public class ExportToExcel<T>
    {
        private IEnumerable<T> data;

        public ExportToExcel(IEnumerable<T> inputCollection)
        {
            this.data = inputCollection;               

            // Run in Debug Mode (F5) and see results when clicking ActionLink.
            Debug.WriteLine("Object: {0}", data.GetType());
            Debug.WriteLine("RowCount: {0}", data.Count());

            // TODO: place my "export to excel" commands here.
        }    
    }
}