C# 无法从类内调用方法?
当我尝试运行我的代码时,我收到错误消息“方法'talk'的No重载包含0个参数”,请有人帮助我调用talk方法。抱歉,代码太多了,但我真的不明白我是否出错了C# 无法从类内调用方法?,c#,visual-studio-2010,C#,Visual Studio 2010,当我尝试运行我的代码时,我收到错误消息“方法'talk'的No重载包含0个参数”,请有人帮助我调用talk方法。抱歉,代码太多了,但我真的不明白我是否出错了 class Program { public void Main(string[] args) { Critter newcritter = new Critter(); Console.WriteLine("Enter critter name: "); var newn
class Program
{
public void Main(string[] args)
{
Critter newcritter = new Critter();
Console.WriteLine("Enter critter name: ");
var newname = Convert.ToString(Console.ReadLine());
newcritter.Name = newname;
Console.WriteLine("Say Hello to your new critter, {0}!", newcritter.Name);
var option = Convert.ToString(Console.ReadLine());
while (option != "0")
{
Console.WriteLine(@"
Critter Caretaker
0 - Quit
1 - Listen to your critter
2 - Feed your critter
3 - Play with your critter
");
if (option == "0")
{
Console.WriteLine("Good-bye.");
}
if (option == "1")
{
newcritter.talk();
}
class Critter
{
public string Name { get; set; }
public int Hunger = 0;
public int Boredom = 0;
public void PassTime()
{
Hunger += 1;
Boredom += 1;
}
public void mood()
{
var unhappiness = Hunger + Boredom;
string m = "";
if (unhappiness < 5)
{
m = "Happy";
}
if (unhappiness <= 5 &&
unhappiness <= 10)
{
m = "Okay";
}
if (unhappiness <= 11 &&
unhappiness <= 15)
{
m = "Frustrated";
}
if (unhappiness <= 16)
{
m = "Mad";
}
}
public void talk(string m)
{
Console.WriteLine("I'm", Name, "and I feel", m, "now.\n");
PassTime();
}
你打电话给newcritter.talk;没有参数,而您的方法需要一个参数public void talkstring m
因此,需要将参数字符串传递给talk方法:
talk方法需要一个字符串参数,因此需要提供一个:
newcritter.talk("fine");
而且,你在这里打电话的方式是错误的。请尝试以下方法:
public void talk(string m)
{
Console.WriteLine("I'm {0} and I feel {1} now.", Name, m);
PassTime();
}
错误更清楚地描述了它:
没有具有0个参数的方法对话:
我认为:
if (option == "1")
{
newcritter.talk();//error here as there no zero argument talk() method
}
应该是:
if (option == "1")
{
newcritter.talk("somestring");
}
下面是一行代码调用talk:
if (option == "1")
{
newcritter.talk();
}
以下是您对谈话的定义:
public void talk(string m)
我认为错误很明显。您在这段代码中遗漏了一些东西。您尚未指定需要执行的操作。 正如我所理解的,你在程序课上的时间应该是
while (option != "0")
{
Console.WriteLine(@"
Critter Caretaker
0 - Quit
1 - Listen to your critter
2 - Feed your critter
3 - Play with your critter
");
if (option == "0")
{
Console.WriteLine("Good-bye.");
}
if (option == "1")
{
newcritter.talk();
}
if (option == "2")
{
newcritter.PassTime();
}
if (option == "3")
{
newcritter.mood();
}
}
你的Crtter课程应该是
class Critter
{
public string Name { get; set; }
public int Hunger = 0;
public int Boredom = 0;
public string m = "Happy";
// No Change in PassTime() method and mood() method
//
public void talk()
{
Console.WriteLine("I'm", Name, "and I feel", m, "now.\n");
PassTime();
}
class Critter
{
public string Name { get; set; }
public int Hunger = 0;
public int Boredom = 0;
public string m = "Happy";
// No Change in PassTime() method and mood() method
//
public void talk()
{
Console.WriteLine("I'm", Name, "and I feel", m, "now.\n");
PassTime();
}