gpt4 book ai didi

vb.net - 使用 VB.Net 的 NerdDinner 验证问题

转载 作者:行者123 更新时间:2023-12-04 07:08:12 25 4
gpt4 key购买 nike

新手问题。我正在 VB.Net 中编写一个 ASP.Net MVC 应用程序,并且一直在使用 NerdDinner 作为示例(在 C# 中)。我一直坚持验证过程,特别是 Models\Dinner.cs 中的代码。我曾尝试使用 http://www.developerfusion.com/tools/convert/csharp-to-vb/ 将其转换为 VB.Net但它阻塞了在 GetRuleViolations 方法中找到的 Yield 语句(参见下面的代码)。所以我的问题是你将如何在 VB.Net 中做同样的事情?

命名空间 NerdDinner.Models {

[Bind(Include="Title,Description,EventDate,Address,Country,ContactPhone,Latitude,Longitude")]
public partial class Dinner {

public bool IsHostedBy(string userName) {
return HostedBy.Equals(userName, StringComparison.InvariantCultureIgnoreCase);
}

public bool IsUserRegistered(string userName) {
return RSVPs.Any(r => r.AttendeeName.Equals(userName, StringComparison.InvariantCultureIgnoreCase));
}

public bool IsValid {
get { return (GetRuleViolations().Count() == 0); }
}

public IEnumerable<RuleViolation> GetRuleViolations() {

if (String.IsNullOrEmpty(Title))
yield return new RuleViolation("Title is required", "Title");

if (String.IsNullOrEmpty(Description))
yield return new RuleViolation("Description is required", "Description");

if (String.IsNullOrEmpty(HostedBy))
yield return new RuleViolation("HostedBy is required", "HostedBy");

if (String.IsNullOrEmpty(Address))
yield return new RuleViolation("Address is required", "Address");

if (String.IsNullOrEmpty(Country))
yield return new RuleViolation("Country is required", "Address");

if (String.IsNullOrEmpty(ContactPhone))
yield return new RuleViolation("Phone# is required", "ContactPhone");

if (!PhoneValidator.IsValidNumber(ContactPhone, Country))
yield return new RuleViolation("Phone# does not match country", "ContactPhone");

yield break;
}

partial void OnValidate(ChangeAction action) {
if (!IsValid)
throw new ApplicationException("Rule violations prevent saving");
}
}

}

最佳答案

在 VB 中获得“完全等效”将需要您使用状态值和 switch 语句对 IEnumerator(of RuleViolation) 进行自定义实现。然而,对于这么简单的事情,那将是矫枉过正。

您可以通过创建一个列表并像这样填充它来获得“几乎等效”的版本:

public function GetRuleViolations() as IEnumerable(of RuleViolation)
dim ret = new List(of RuleViolation)();

'replace the ... with the appopriate logic from above.
if ... then
ret.Add(...)
end if

return ret
end function

这比 C# 版本效率稍低,因为它创建一个列表并一次返回所有项目,而 C# 版本在执行“foreach”语句时即时返回每个项目。在这种情况下,列表很小,所以没什么大不了的。

关于vb.net - 使用 VB.Net 的 NerdDinner 验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/782848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com