1

在完成 ASP MVC 3 音乐商店教程时,我正在尝试将 C# 页面翻译成 VB。http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-4

该页面是一堆将被拉入数据库的示例数据。

我要翻译的 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" },

         //lots of albums here... just like examples above and below

            new Album { Title = "Ao Vivo [IMPORT]", Genre = genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = artists.Single(a => a.Name == "Zeca Pagodinho"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
        }.ForEach(a => context.Albums.Add(a));

我转换后的 VB 代码看起来像这样,但编译器说第一行有语法错误...

New List(Of Album)() With { _             //Compiler says there is a syntax error here
            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" _
            }, _

       //lots of albums here 

            New Album() With { _
                .Title = "Ao Vivo [IMPORT]", _
                 .Genre = genres.[Single](Function(g) g.Name = "Latin"), _
                 .Price = 8.99D, _
                 .Artist = artists.[Single](Function(a) a.Name = "Zeca Pagodinho"), _
                 .AlbumArtUrl = "/Content/Images/placeholder.gif" _
             } _
}.ForEach(Function(a) context.Albums.Add(a))

如何修复语法错误?

4

2 回答 2

2

您需要(至少)在构造周围加上括号,并且我认为还Call需要一个(至少在以前的 VB 版本中需要,如果 VB10 仍然需要它,我现在不需要);此外,With列表构造函数之后应该是 aFrom(但在其他构造函数之后是必需的):

Call (New List(Of Album) From { _
    …
}).ForEach(…)

此外,ForEach需要 a Sub,而不是 a Function。(顺便说一下,行继续下划线在 VB10 中是多余的。)

但在 VB 和 C# 中,这都是非常混乱的代码。只需将表达式分配给其初始化程序中的对象,然后在该对象ForEach调用.

于 2012-08-09T15:44:27.007 回答
2

在我看来,你像一个额外的With和一组额外的花括号。我认为你的语法应该是这样的:

 New List(Of SomeThing)(
     {
     New SomeThing With {.name = "foo"}, 
     New SomeThing With {.name = "bar"}
     }
 )

所以你的例子应该是这样的:

    Dim a As New List(Of Album)({
          New Album() With {.Title = "A Copland Celebration, Vol. I"},
          New Album() With {.Title = "Ao Vivo [IMPORT]"}})

但我同意康拉德的观点——这段代码太可怕了!

于 2012-08-09T15:50:45.490 回答