gpt4 book ai didi

c# - 如何在类构造函数参数中使用 IEnumerable

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:52 28 4
gpt4 key购买 nike

我正在尝试使我的 MVC Controller (导出到 Excel)中的一些代码更通用,因为我已经到了在多个 Controller 中键入几乎相同代码的地步。为了使导出到 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.
}
}
}

最佳答案

您需要在某处定义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.
}
}
}

关于c# - 如何在类构造函数参数中使用 IEnumerable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34467635/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com