c# - 关于泛型类型的澄清

标签 c# .net generics

鉴于下面的代码块(来源:http://www.asp.net/learn/mvc/tutorial-31-cs.aspx)...我收到此错误:使用泛型类型“System.Collections.Generic.List”需要“1”类型参数

我可以通过简单地将我的声明修改为:var groups = new List<string>();来解决这个问题。这只是示例代码中语法无效的情况吗?不过,我在这里问这个问题是因为我不止一次遇到过这种情况,并且想知道是否有某种 VS.NET“严格性设置”可能在我的 VS 环境中发挥作用。

public class GroupController : Controller
{
    public ActionResult Index()
    {
        var groups = new List();
        return View(groups);
    }

    /// another example...
    Assert.IsInstanceOfType(result.ViewData.Model, typeof(IEnumerable));  // same error

    Assert.IsInstanceOfType(result.ViewData.Model, typeof(IEnumerable<string>)); // corrected

}

最佳答案

链接网页中有错误。如果您查看 HTML 源代码,您可以看到泛型类型参数有一个参数:

namespace ContactManager.Controllers
{
    public class GroupController : Controller
    {
        public ActionResult Index()
        {
            var groups = new List<Group>();
            return View(groups);
        }

    }
}

同样适用于上面的示例(或者,在您的问题中,下面):

// Assert
Assert.IsInstanceOfType(result.ViewData.Model, typeof(IEnumerable<Group>));

关于c# - 关于泛型类型的澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1841596/

相关文章:

c# - 可以让 Asp.Net Core 中的 Swagger 为非 MVC Controller 的类生成文档吗

c# - 如何将控制台 C# 程序的输入和输出重定向到套接字?

c# - 使用 MSI 将 .NET 程序集安装到 GAC

c# - C#中_bstr_t的等价物是什么

delphi - 在 Delphi XE 中高效更改泛型中的记录成员

swift - 如何将类型为 Class<Class Implementing Protocol> 的值存储在类型为 [String :Class<Protocol>] in Swift? 的字典中

c# - 间歇性 "unable to connect to remote server"错误

c#类工厂新手

c# - 无法将类型 'T' 隐式转换为 'Int'

.net - 中止阻塞线程