2017-04-04 76 views
2

我在這裏丟失了什麼。C#7使用模式匹配不起作用

的Visual Studio告訴我使用內聯模式匹配,並重新編寫代碼爲我,但是當它出現錯誤:

Severity Code Description Project File Line Suppression State Error CS8121 An expression of type TReturnState cannot be handled by a pattern of type LightState. DataModels C:\Users\Michael\Documents\windows\GCMS UWP\Models\Models\Elements\Lights\Light.cs 77 Active

這裏是原代碼:

public override void UpdateState<TReturnState>(TReturnState returnState) 
    { 
     var newState = returnState as LightState; 

     if (newState != null) 
      State = newState; 

     base.UpdateState(returnState); 
    } 

這就是當VS爲我重做它時的樣子。

public override void UpdateState<TReturnState>(TReturnState returnState) 
    { 
     if (returnState is LightState newState) 
      State = newState; 

     base.UpdateState(returnState); 
    } 

我更喜歡調整的方式,但我得到的錯誤。我錯過了什麼或者這是一個錯誤?

包我使用:

"dependencies": { 
    "Microsoft.NETCore.UniversalWindowsPlatform": "5.3.1", 
    "Newtonsoft.Json": "9.0.1", 
    "System.ValueTuple": "4.3.0" 
    }, 
+0

'State =(LightState)newState;' – Hogan

+1

@SirRufo它怎麼沒用它更新一個叫做「State」的全局變量? – Hogan

+0

@Hogan哎呀,你是對的...... o) –

回答

4

由於@SirRufo它似乎是在C#中的已知的bug評論指出,7

的修復是寫與投代碼到目的。

public override void UpdateState<TReturnState>(TReturnState returnState) 
    { 
     if ((object)returnState is SpeakerState newState) 
      State = newState; 

     base.UpdateState(returnState); 
    } 

但是;這不是一個真正的修復,而是一個破解bug的黑客。 Visual Studio也告訴我,這個轉換爲對象是不必要的,並嘗試修復它,但是當它再次出現錯誤時。

這會對通過Visual Studio進行的完整代碼重構產生阻礙作用。

Link to known issue posted by Sir Rufo.

編輯:升級到C#7.1的修復拳擊模式匹配匿名類型,它現在就像它應該無開銷的這個問題。

+0

使用你的方法,但沒有爲我工作,也更新Visual Studio到15.3.5版本沒有工作 –

+0

@MohammadSadeghipour升級到C#7.1。它現在正確地模式匹配它應該的匿名類型。 –

+0

我按照你的說法做了,但仍然無法處理以下錯誤: 錯誤CS1617:/ langversion的選項'7.1'無效;必須是ISO-1,ISO-2,默認值或範圍爲1到6的整數。 –