在 C# 中,错误“对象引用非静态字段、方法或属性需要...”在尝试从静态方法访问非静态成员时出现。发生此错误的原因是静态方法无法访问特定于实例的数据。
在提供的代码片段中,问题出现在声明为静态的“Main”方法中,而“volteado”和“siprimo”方法是非静态的。要解决此错误,必须将“siprimo”和“volteado”方法声明为静态。通过添加“static”关键字,可以在静态“Main”方法中直接访问这些方法。这是更正后的代码:
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.Write("Write a number: "); long a = Convert.ToInt64(Console.ReadLine()); // a is the number given by the user long av = volteado(a); // av is "a" but swapped if (siprimo(a) == false && siprimo(av) == false) Console.WriteLine("Both original and swapped numbers are prime."); else Console.WriteLine("One of the numbers isn't prime."); Console.ReadLine(); } private static bool siprimo(long a) // Declare siprimo as static { // Evaluate if the received number is prime bool sp = true; for (long k = 2; k <= a / 2; k++) if (a % k == 0) sp = false; return sp; } private static long volteado(long a) // Declare volteado as static { // Swap the received number long v = 0; while (a > 0) { v = 10 * v + a % 10; a /= 10; } return v; } } }
以上是为什么在 C# 中从静态方法调用非静态方法时会出现'需要对象引用...”?的详细内容。更多信息请关注PHP中文网其他相关文章!