我正在尝试在C#中创建一个控制台二次方计算器。
但是出现错误“访问非静态成员需要对象引用”
在带有变量“A”,“B”和“C”的行上;
但是,当我在MainClass类中添加static时,
Xamarin Studio给我“无法在静态类中声明实例成员”
我要放弃在查找后尝试解决此问题的要点
如果您能告诉我在哪里更改代码以及为什么这样做不起作用,将不胜感激。
using System;
namespace CsharpConceptsCrashCourse
{
class MainClass
{
double A, B, C;
public static void Main (string[] args)
{
Begin ();
Console.WriteLine("Root 1 : {0}, Root 2: {1}",
QRoot(A,B,C,"NEG"),QRoot(A,B,C,"POS"));
Console.ReadKey ();
}
public static double QRoot(double a,double b,double c, string VL){
double top = Math.Pow (b, 2) - (4 * a * c);
if (VL == "POS") {
double topf = (-1 * (b)) + Math.Sqrt (top);
return (topf / (2 * a));
} else{
double topf = (-1 * (b)) - Math.Sqrt (top);
return (topf / (2 * a));
}
}
public static void Begin(){
Console.WriteLine ("Welcome to the quadratic calculator:");
Console.WriteLine ("Enter your three values for \na , b, and c \nfrom the standard format");
Console.WriteLine ("A:");
A = Convert.ToDouble (Console.ReadLine ());
Console.WriteLine ("B:");
B = Convert.ToDouble (Console.ReadLine ());
Console.WriteLine ("C:");
C = Convert.ToDouble (Console.ReadLine ());
}
}
}
最佳答案
发生此错误的原因是您的Main
方法是static
:
public static void Main (string[] args)
{
...
}
并且在该静态方法中,您尝试访问非静态成员:
double A, B, C;
这是不可能的,因为只能通过类的实例访问非静态实例成员。
因此,直接的解决方案是也声明这些成员
static
:class MainClass
{
static double A, B, C;
...
}
关于c# - Tamarin Studio中出现关于 “Cannot Declare Instance Members in Static Class”的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36160020/