我有如下的switch陳述句(用這個對我來說是新的語法)。
我在一個靜態類中也有如下的Dictionary / Enum。
Switch陳述句 :
public static Dictionary< string, string> MyMethod(string brands, int templateIndex, long accountId)
{
return accountId switch
{
AccountsId[AccountLang.French] => Fr.GetContent(templateIndex, brands),
AccountsId[AccountLang.Spanish] => ES.GetContent(templateIndex, brands),
_ => throw new Exception($"Account Id not found {typeof(LangHelper)}">)
};
}
Dictionary / Enum:
public static readonly Dictionary< AccountLang, long> AccountsId = new Dictionary<AccountLang, long> ()
{
{AccountLang.French , 25****** },
{AccountLang.Spanish , 55****** },
};
public enum AccountLang
{
法語。
西班牙語。
}
而這里是我的3個錯誤,都是針對開關情況下的AccountsId[AccountLang.French]:
Error CS0246 The type or namespace name 'AccountsId' could not be found (are you missing a using directive or an assembly reference?)
錯誤 CS8121 型別為'long'的運算式不能被型別為'AccountsId[]'的模式處理。
錯誤 CS0270 陣列大小不能在變數宣告中指定(嘗試用'new'運算式來初始化)
如果我在switch case中使用這種語法,我也有同樣的錯誤,但在編譯時 :
如果我像這樣放置命名空間和類 我在這里錯過了什么,看起來第一個問題是因為它找不到 uj5u.com熱心網友回復: 你使用的不是switch陳述句,而是switch運算式。從檔案中可以看出: 每個開關運算式臂包含一個模式、一個可選的case guard、=>標記和一個運算式。 模式被列舉為 在這些結構中,你可以將一個輸入運算式與以下任何一種模式相匹配
以下模式進行匹配: 在你的示例代碼中,你正在使用一個運行時值來代替模式。這不符合上述任何類別的要求。
最簡單的修復方法是改變字典的順序,這樣你就可以從帳戶 ID 進行語言查詢。如果需要,這個語言列舉可以用在一個開關中,以備你需要在列舉和你的翻譯之間進行映射。
標籤:long aId是一個長條形的變數,但它的大小是一樣的。
long aId when AccountsId[AccountLang.French] == aId => Fr.GetContent(templateIndex, brands)NamespaceName.className.NameAccountsId,它的問題是一樣的AccountsId字典,但如果我在switch case之外使用它,它就會完美地作業。
