简体   繁体   中英

An error message is throwing off about “Cannot Declare Instance Members in Static Class” in Tamarin Studio

I am trying to create a console Quadratic Calculator in C#. However errors "An object reference is required to access non - static members" on the lines with the variable "A" "B" and "C"; However when I add static to the MainClass Class, Xamarin Studio is giving me "Cannot declare instance members in a static class"

I am to the point of giving up on trying to solve this issue after looking it up

It would be really appreciated if you could tell me where to change the code and why this does not work;

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 ());
    }
}

}

The reason for this error is your Main method is static :

public static void Main (string[] args)
{
    ...
}

and in that static method you are trying to access non-static members :

double A, B, C;

This is impossible, since non-static instance members can only be accessed through an instance of your class.
So the immediate solution is to declare those members static , too:

class MainClass
{
    static double A, B, C;
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM