c# - Tamarin Studio中出现关于 “Cannot Declare Instance Members in Static Class”的错误消息

标签 c# methods compiler-errors

我正在尝试在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/

相关文章:

c# - 如何在 C# 中将 List<byte> 转换为 byte[]?

c# - .netcore TestScheduler 的 Nuget 包

java - 调用内部带有 for 循环的方法,而不更新变量

java - 如何只返回以标点符号结尾的字符串?

C++ lambda 表达式无法编译

compiler-errors - Mathematica : 'Findroot' not returning expected result

c# - 如何使用C#查找音乐文件夹目录?

c# - 找不到类型或命名空间名称 'Column'

java - 将值从构造函数传递到方法

c++ - #include <WinUsb.h> 在 MFC 应用程序中产生编译器错误