我正在学习MVC3并同时从C#过渡到VB.NET(有趣,我知道)。我正在通过MvcMusicStore示例来学习MVC3。所有样本都在C#中,所以我将它们转换为VB。我遇到了一段我无法直接转换的代码,不得不稍微改变以使其工作。
我不知道为什么一种方式有效而另一种方式无效。
这不起作用:
Dim albums = New List(Of Album)() From { _
New Album() With { _
.Title = "A Copland Celebration, Vol. I", _
.Genre = genres.[Single](Function(g) g.Name = "Classical"), _
.Price = 8.99D, _
.Artist = artists.[Single](Function(a) a.Name = "Aaron Copland & London Symphony Orchestra"), _
.AlbumArtUrl = "/Content/Images/placeholder.gif" _
}, _
... [MORE INSTANCES]
}.ForEach(Sub(a) context.Albums.Add(a))
然而,这确实有效:
Dim albums = New List(Of Album)() From { _
New Album() With { _
.Title = "A Copland Celebration, Vol. I", _
.Genre = genres.[Single](Function(g) g.Name = "Classical"), _
.Price = 8.99D, _
.Artist = artists.[Single](Function(a) a.Name = "Aaron Copland & London Symphony Orchestra"), _
.AlbumArtUrl = "/Content/Images/placeholder.gif" _
}, _
... [MORE INSTANCES]
}
albums.ForEach(Sub(a) context.Albums.Add(a))
两者之间的区别在于,第一个应用ForEach创建集合,而第二个应用ForEach作为单独的调用。
为什么这会有所不同?
编辑:添加原始C#代码
编译器不会在这里抱怨。
new List<Album>
{
new Album { Title = "A Copland Celebration, Vol. I", Genre = genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = artists.Single(a => a.Name == "Aaron Copland & London Symphony Orchestra"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
... [MORE INSTANCES]
}.ForEach(a => context.Albums.Add(a));
答案 0 :(得分:2)
ForEach()方法的返回类型为void
,因此不返回任何内容,因此您无法将调用结果分配给变量。
答案 1 :(得分:2)
很确定你的问题在这里:
Dim albums =
您正在尝试将ForEach操作的结果分配给变量albums
。 ForEach
不会返回任何内容,因此您无法将作业转移到albums
。