C# 错误是什么“;需要对象引用” ;什么意思?
我的C#代码有一个问题-不知怎么的,我无法让我的开关工作,(例如案例1:Charmander();break;)说“非静态字段、方法或属性“Program.Charmander()”需要对象引用”-但我似乎无法理解为什么它没有被引用C# 错误是什么“;需要对象引用” ;什么意思?,c#,reference,C#,Reference,我的C#代码有一个问题-不知怎么的,我无法让我的开关工作,(例如案例1:Charmander();break;)说“非静态字段、方法或属性“Program.Charmander()”需要对象引用”-但我似乎无法理解为什么它没有被引用 class Program { string[] PokemonList = // Entries i vores array af tilfældige Pokémon { "Charma
class Program
{
string[] PokemonList =
// Entries i vores array af tilfældige Pokémon
{ "Charmander", "Squirtle", "Bulbasaur", "Pikachu", "Eevee", "Gastly", "Jigglypuff" };
int index = 0;
static void Main(string[] args)
{
// array "køn"
string[] gen = { "♂", "♀" };
// Oprettelse af vores array "PokemonList"
string[] PokemonList =
// Entries i vores array af tilfældige Pokémon
{ "Charmander", "Squirtle", "Bulbasaur", "Pikachu", "Eevee", "Gastly", "Jigglypuff" };
foreach (string PokemonSelect in PokemonList)
// Prints the name of all selectable Pokémon
Console.WriteLine(PokemonSelect);
Console.WriteLine("Which Pokémon will you choose?");
//Chooses a random Pokémon from the string PokemonList
Random RandomPokemon = new Random();
int index = RandomPokemon.Next(PokemonList.Length);
Console.WriteLine($"Your opponent is {PokemonList[index]}");
//Menu over choices the user can press
string StringMenu = Console.ReadLine();
int NextChoice = Convert.ToInt32(StringMenu);
switch (NextChoice)
{
case 1:
Charmander();
break;
case 2:
Squirtle();
break;
case 3:
Bulbasaur();
break;
case 4:
Pikachu();
break;
case 5:
Eevee();
break;
case 6:
Gastly();
break;
case 7:
Jigglypuff();
break;
}
Console.WriteLine("Your Pokémon's gender is: " + gen[new Random().Next(0, gen.Length)]);
}
public string Charmander()
{
Console.WriteLine("You choose: Charmander");
return PokemonList[index];
}
public string Squirtle()
{
Console.WriteLine("You choose: {1}");
return PokemonList[index];
}
public string Bulbasaur()
{
Console.WriteLine("You choose: {2}");
return PokemonList[index];
}
public string Pikachu()
{
Console.WriteLine("You choose: {3}");
return PokemonList[index];
}
public string Eevee()
{
Console.WriteLine("You choose: {4}");
return PokemonList[index];
}
public string Gastly()
{
Console.WriteLine("You choose: {5}");
return PokemonList[index];
}
public string Jigglypuff()
{
Console.WriteLine("You choose: {6}");
return PokemonList[index];
}
}
}
您的
Main
方法是static
(因此:不与任何对象实例关联);您正在尝试调用实例方法Charmander
等
你的意思是在程序的哪个实例上?你实际上没有创建任何实例。因此:在这种情况下,这些方法可能也是静态的。或者,你需要在某个地方创建一个实例,并使用它。因为你有一个可变字段(索引
),这可能是更好的方法。例如:
static void Main(字符串[]args)
{
新程序().DoTheThing();
}
void DoTheThing()//命名很难
{
//数组“køn”
字符串[]gen={”♂", "♀" };
//Oprettelse af vores阵列“口袋妖怪列表”
...
我可能也会将这里的逻辑移出程序
类,让它执行实际的启动/args处理,因此:
static void Main(字符串[]args)
{
新口袋妖怪();
}
并将DoTheThing
移动到类PokemonWhatever
(并将其公开
或内部
)公开静态字符串Charmander()
您还需要将PokemonList
和索引
设置为静态。或者将它们传递给这些方法。将这些方法设置为静态Charmander()水仙花;