C# ошибки CS1026, CS0103 и CS1525
Делаю метод который принимает на вход фамилию семьи и возвращает одно из трех значений: "friend", "enemy", "neutral". Правила определения:
Друзья ("friend"): "Karstark", "Tally"
Враги ("enemy"): "Lannister", "Frey"
Любые другие семьи считаются нейтральными
class App
{
// BEGIN (write your solution here)
public static string WhoIsThisHouseToStarks(string Subname)
{
var familyType = "";
if (Subname == "Karstark", "Tally")
{
familyType = "friend";
}
else if (Subname == "Lannister", "Frey")
{
familyType = "enemy";
}
else
{
familyType = "neutral";
}
return familyType;
}
// END
}
В итоге выпадает следующая ошибка:
(7,33): error CS1026: Unexpected symbol `,', expecting `)'
(7,42): error CS1026: Unexpected symbol `)', expecting `)'
(11,8): error CS1525: Unexpected symbol `else'
(11,39): error CS1026: Unexpected symbol `,', expecting `)'
(11,47): error CS1026: Unexpected symbol `)', expecting `)'
(15,8): error CS1525: Unexpected symbol `else'
(1,16): error CS0103: The name `App' does not exist in the current context
(1,23): error CS0103: The name `actual1' does not exist in the current context
(1,16): error CS0103: The name `App' does not exist in the current context
(1,23): error CS0103: The name `actual2' does not exist in the current context
(1,16): error CS0103: The name `App' does not exist in the current context
(1,23): error CS0103: The name `actual3' does not exist in the current context
(1,16): error CS0103: The name `App' does not exist in the current context
(1,23): error CS0103: The name `actual4' does not exist in the current context
(1,16): error CS0103: The name `App' does not exist in the current context
(1,23): error CS0103: The name `actual5' does not exist in the current context
make: *** [Makefile:2: test] Error 1
#<Process::Status: pid 169601 exit 2>
Ответы (1 шт):
Автор решения: Alexander Petrov
→ Ссылка
Это записывается так:
public static string WhoIsThisHouseToStarks(string subname)
{
if (subname == "Karstark" || subname == "Tally")
return "friend";
if (subname == "Lannister" || subname == "Frey")
return "enemy";
return "neutral";
}
Если значений для проверки будет много, то условное выражение станет очень громоздким. В таком случае можно эти значения сохранить в какую-либо коллекцию и использовать метод Contains:
static string[] friends = new[] { "Karstark", "Tally" };
static string[] enemies = new[] { "Lannister", "Frey" };
public static string WhoIsThisHouseToStarks_2(string subname)
{
if (friends.Contains(subname))
return "friend";
if (enemies.Contains(subname))
return "enemy";
return "neutral";
}
И вариант с паттерн-матчингом, где доступны контекстуальные ключевые слова and и or:
public static string WhoIsThisHouseToStarks_3(string subname)
{
if (subname is "Karstark" or "Tally")
return "friend";
if (subname is "Lannister" or "Frey")
return "enemy";
return "neutral";
}