2009-04-23 47 views
2

新手問題。我在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中做同樣的事情?使用VB.Net的NerdDinner驗證問題

命名空間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"); 
    } 
} 

}

+0

什麼限制你在C#中使用它? – 2009-04-23 18:15:13

回答

3

在VB中獲得「完全等價」將需要您使用狀態值和switch語句自定義實現IEnumerator(的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#版本efficent略少,因爲它會創建一個列表,並返回所有項目一次,隨着「foreach」語句正在執行,C#版本隨即返回每個項目。在這種情況下,名單很小,所以這不是什麼大問題。

+0

謝謝斯科特,我會試試這個 – 2009-04-23 19:01:26

0

不幸的是,沒有等同於在VB.Net yield語句。

+1

A給了這個-1。在VB中有一個等價於「yield」的值,但它需要用手寫的IEnumerator(T)實現。這是令人討厭的,耗時,但它是可能的。 – 2009-04-23 18:06:56