我是 C# 的新手,我正在制作一个小应用程序来检查控制台的输入是否为回文。我自己走了很远,但我遇到了一个错误。
代码:
class Program
{
static void Main(string[] args)
{
string str;
Console.WriteLine("Voer uw woord in:");
str = Console.ReadLine();
if (isPalindroom(str) == true)
{
Console.WriteLine(str + " is een palindroom");
}
else
{
Console.WriteLine(str + " is geen palindroom");
}
}
bool isPalindroom(String str)
{
string reversedString = "";
for (int i = str.Length - 1; i >= 0; i--)
{
reversedString += str[i];
}
if (reversedString == str)
{
return true;
}
else
{
return false;
}
}
}
我收到这个错误:
Error 1 An object reference is required for the non-static field, method, or property 'ConsoleApplication2.Program.isPalindroom(string)' snap 17 17 ConsoleApplication2
位于:
if (isPalindroom(str) == true)
如果你能帮我一点忙,我会很高兴:)
最佳答案
只需将 static
修饰符添加到您的 isPalindroom
方法即可。
如果不这样做,isPalindroom
将是一个“实例”方法,可以在 Program
实例上调用。
简单来说,因为您没有 Program 类型的变量(main 方法本身是静态的),您不能调用非静态方法。
可以在类型本身 (Program.isPalydroom(xxx)
) 或类中的任何其他方法上调用静态方法。
关于c# - 回文 - 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12265419/