Создание экземпляра класса в методе main в C#, ошибки CS0120 и предупреждение CS0169 - PullRequest
0 голосов
/ 19 января 2020

Я пытаюсь создать экземпляр класса в методе main с помощью конструктора (я удалил stati c в методах выше), но не могу понять, как его активировать с помощью экземпляра. Пожалуйста, помогите, спасибо.

Это код, который я использую, и я сделал скриншот ошибок, которые я получаю.

using System;

namespace CalculatorTest
{
    class Calculator
    {
        public int operand1;
        public int operand2;

        public Calculator(int operand1, int operand2, int s, int n)
        {
            this.operand1 = operand1;
            this.operand2 = operand2;
        }

        public string WriteText(string s)
        {
            return s;
        }
        public int WriteNumber(int n)
        {
            return n;            
        }
    }
    class Program    
    {
        private static int operand1;
        private static int operand2;

        public static void Main(string[] args)
        {                
            string s = Calculator.WriteText("Hello world!");
            Console.WriteLine(s);

            int n = Calculator.WriteNumber(53 + 28);
            Console.WriteLine(n);

            Console.Read();
        }
    }
}

enter image description here

1 Ответ

1 голос
/ 19 января 2020

Вы должны создать экземпляр Calculator (и передать значения operand в конструктор), прежде чем обращаться к его нестационарным c методам. Также имеет смысл удалить параметры s и n из конструктора, поскольку вы передали их методам

class Calculator
{
    private int operand1;
    private int operand2;

    public Calculator(int operand1, int operand2)
    {
        this.operand1 = operand1;
        this.operand2 = operand2;
    }

    public string WriteText(string s)
    {
        return s;
    }
    public int WriteNumber(int n)
    {
        return n;            
    }
}
var calculator = new Calculator(operand1, operand2);
string s = calculator .WriteText("Hello world!");
Console.WriteLine(s);

int n = calculator .WriteNumber(53 + 28);
Console.WriteLine(n);
...