无法从“System.Collections.Generic.IList<>”转换为“”

本文关键字:IList 转换 Generic System Collections | 更新日期: 2023-09-27 18:32:36

[NonAction]
protected void PrepareNewsCommentModel(NewsCommentModel model, NewsComment newsComment)
{
  if (newsComment == null) throw new ArgumentNullException("newsComment");
  if (model       == null) throw new ArgumentNullException("model");
  model.Id = newsComment.Id;
  model.CommentTitle = newsComment.CommentTitle;
  model.CustomerName = newsComment.CustomerName;
  model.CommentText = newsComment.CommentText;
}
public ActionResult Comments(int number)
{
  if (!_newsSettings.Enabled)
    return RedirectToRoute("HomePage");
  var newsComment = _newsService.GetNewsComment(number);
  var model = new NewsCommentModel();
  PrepareNewsCommentModel(model,newsComment);
  return View(model);
}

这是我的错误:

Error 2 Argument 2: cannot convert from
'System.Collections.Generic.IList<Yapi.Core.Domain.News.NewsComment>' to
'Yapi.Core.Domain.News.NewsComment'
D:'YAPI'Projects'ASCS-Portal'Yapi.Web'Controllers'NewsController.cs 420
40
Yapi.Web

无法从“System.Collections.Generic.IList<>”转换为“”

错误告诉您问题。 newsComment是一种IList<NewsComment>但您的PrepareNewsCommentModel方法需要NewsComment

尝试使用 Linq 的 First 扩展方法:

var newsComment = _newsService.GetNewsComment(number).First();

或者FirstOrDefault您的GetNewsComment方法是否可以返回空列表:

var newsComment = _newsService.GetNewsComment(number).FirstOrDefault();
相关文章: