You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用List集合添加对象时出错:无法将void转换为自定义模型类

解决List集合初始化时的"无法将void转换为自定义模型类"错误

嘿,这个问题我之前开发ASP.NET MVC的时候也踩过坑!咱们来一步步拆解问题根源,然后搞定它。

错误原因

你写的这行代码出了问题:

List<Projects> pro = new List<Projects>() { pro.Add(startupboost) };

List<T>.Add()方法的返回值是**void**(没有返回值),但集合初始化器{ ... }里需要的是Projects类型的实例。编译器看到你把一个void类型的操作放进去,自然会报错——它没法把"无返回值"转换成你的自定义Projects模型类。

正确的两种写法

写法一:直接用集合初始化器添加对象

集合初始化器的本质是帮你自动调用Add方法,所以直接把实例放进去就行:

public ActionResult Index() {
    Projects startupboost = new Projects( 
        "startupboost", 
        "StartUp Boost", 
        "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.", 
        "WordPress, Custum built WP plugins, AJAX, PHP, MYSQL, JAVASCRIPT, jQUERY, SASS", 
        "http://startupboost.dk/"
    );
    // 直接把对象放进初始化器里
    List<Projects> pro = new List<Projects>() { startupboost };
    // 记得把列表传给视图,不然视图拿不到数据哦
    return View(pro);
}

写法二:先创建空列表,再手动调用Add方法

如果你更习惯分步操作,也可以先初始化空列表,再添加对象:

public ActionResult Index() {
    Projects startupboost = new Projects( 
        "startupboost", 
        "StartUp Boost", 
        "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.", 
        "WordPress, Custum built WP plugins, AJAX, PHP, MYSQL, JAVASCRIPT, jQUERY, SASS", 
        "http://startupboost.dk/"
    );
    // 先创建空列表
    List<Projects> pro = new List<Projects>();
    // 再调用Add添加对象
    pro.Add(startupboost);
    return View(pro);
}

额外提醒

如果你的视图是强类型视图(基于List<Projects>),一定要记得把列表作为参数传给View()方法,不然视图里会拿不到数据哦~

内容的提问来源于stack exchange,提问作者Jonas Tamoševičius

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:23:49