2017-10-05 123 views
13

難道有人請幫助啓迪我嗎?無效切換語法生成成功?

我去登記入住TFS的一些變化,我的入住被拒絕了。它促使我看看我編輯的switch語句。

我發現的是,Visual Studio 2017聲稱沒有編譯時問題,並允許我成功構建和部署應用程序。最重要的是,即使是該方法的單元測試似乎也按預期通過了。

public enum PaymentStatus 
{ 
    Issued, 
    Cleared, 
    Voided, 
    Paid, 
    Requested, 
    Stopped, 
    Unknown 
} 

public class PaymentViewModel 
{ 
    public PaymentStatus Status { get; set; } 

    ... 

    public String StatusString 
    { 
     get 
     { 
      switch (this.Status) 
      { 
       case PaymentStatus.Cleared: 
        return "Cleared"; 
       case PaymentStatus.Issued: 
        return "Issued"; 
       case PaymentStatus.Voided: 
        return "Voided"; 
       case PaymentStatus.Paid: 
        return "Paid"; 
       case PaymentStatus.Requested: 
        return "Requested"; 
       case PaymentStatus.Stopped: 
        return "Stopped"; 
       case PaymentStatus Unknown: 
        return "Unknown"; 
       default: 
        throw new InavlidEnumerationException(this.Status); 
      } 
     } 
    } 
} 

所以,請注意,「case PaymentStatus Unknown」行缺少'。'。點運算符。如前所述,該項目建設並運行;但未能通過門控生成服務器簽入。

另外,還要注意以下測試合格:

[TestMethod] 
public void StatusStringTest_Unknown() 
{ 
    var model = new PaymentViewModel() 
    { 
     Status = PaymentStatus.Unknown 
    } 

    Assert.AreEqual("Unknown", model.StatusString); 
} 

這裏有沒有表現出squigglies一些圖像和它確實建立精細: Switch-No-Compiler-Error

而且,經過測試方法: Switch-Passing-Test

最後,請注意,我只用靜態字符串運行測試,而不是使用資源文件並通過測試。在上面的代碼中,爲了簡單起見,我忽略了資源文件的內容。

對此的任何想法都非常感謝!提前致謝!

回答

11

這將編譯因爲你的Visual Studio解釋PaymentStatus Unknown作爲圖案匹配,這是一個new feature C#7:

  • PaymentStatus是類型,
  • Unknown是名字,
  • 沒有條件(即模式總是匹配)。

的預期使用情況這個語法是這樣的:

switch (this.Status) { 
    case PaymentStatus ended when ended==PaymentStatus.Stopped || ended==PaymentStatus.Voided: 
     return "No payment for you!"; 
    default: 
     return "You got lucky this time!"; 
} 

如果TFS被設置爲使用C#的舊版本,它會拒絕這個源。

注意:你的單元測試工作的原因是其餘的情況都是正確的。但是,投擲InavlidEnumerationException(this.Status)的測試用例會失敗,因爲交換機會將任何未知值解釋爲PaymentStatus.Unknown