C#有一个名为yield的关键字.VB.NET缺少这个关键字.Visual Basic程序员如何解决缺少此关键字的问题?他们是否实现了自己的迭代器类?或者他们尝试编码以避免需要迭代器?
该产量关键字不强制编译器做幕后的一些编码.在C#中实现迭代器及其后果(第1部分)就是一个很好的例子.
可能重复:
VB.NET中的产量
在C#中,当编写返回a的函数时IEnumerble<>,您可以使用yield return返回枚举的单个项目并yield break;表示没有剩余项目.做同样事情的VB.NET语法是什么?
NerdDinner代码中的一个示例:
public IEnumerable<RuleViolation> GetRuleViolations() {
if (String.IsNullOrEmpty(Title))
yield return new RuleViolation("Title required","Title");
if (String.IsNullOrEmpty(Description))
yield return new RuleViolation("Description required","Description");
if (String.IsNullOrEmpty(HostedBy))
yield return new RuleViolation("HostedBy required", "HostedBy");
if (String.IsNullOrEmpty(Address))
yield return new RuleViolation("Address required", "Address");
if (String.IsNullOrEmpty(Country))
yield return new RuleViolation("Country required", "Country");
if (String.IsNullOrEmpty(ContactPhone))
yield return new RuleViolation("Phone# required", "ContactPhone");
if (!PhoneValidator.IsValidNumber(ContactPhone, Country))
yield return new RuleViolation("Phone# does not match country", "ContactPhone");
yield break;
}
Run Code Online (Sandbox Code Playgroud)
我最近和Caliburn一起玩.一堆伟大的东西,包括合作例程的实施.
我正在做的大部分工作都是基于C#的,但现在我也正在为基于Rob的小型MVVM框架的VB.NET专卖店创建架构指南.
除了使用VB的协同程序外,一切看起来都很顺利.自从使用VB 10以来,我们可以尝试像Bill McCarthy的建议:
Public Function Lines(ByVal rdr as TextReader) As IEnumerable(Of String)
Return New GenericIterator(Of String)
(Function(ByRef nextItem As String) As Boolean
nextItem = rdr.ReadLine
Return nextItem IsNot Nothing
End Function)
End Function
Run Code Online (Sandbox Code Playgroud)
我只是无法理解如何在VB中编写一个更复杂的常规方法(如Rob的GameLibrary中的方法):
public IEnumerable<IResult> ExecuteSearch()
{
var search = new SearchGames
{
SearchText = SearchText
}.AsResult();
yield return Show.Busy();
yield return search;
var resultCount = search.Response.Count();
if (resultCount == 0)
SearchResults = _noResults.WithTitle(SearchText); …Run Code Online (Sandbox Code Playgroud) 使用下面的C#代码,您将如何在Visual Basic中编写它?它试图说什么?
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace Microsoft.LiveLabs.Pivot
{
/// <summary>
/// Tile Builder class
/// </summary>
public static class TileBuilder
{
/// <summary>
/// Specifies which images are required in the images array used in CreateTile
/// according to the Morton fractal pattern used by Seadragon.
/// </summary>
/// <remarks>
/// Usage of this and CreateTile are kind of tricky. Here's an example:
/// Say you have a results …Run Code Online (Sandbox Code Playgroud) vb.net ×4
c# ×2
yield ×2
.net ×1
caliburn ×1
coroutine ×1
ienumerable ×1
iterator ×1
loops ×1
yield-return ×1