在 C# 的 main 方法中创建 class 实例,错误 CS0120 和警告 CS0169
Creating a class instance in main method in C#, errors CS0120 and warning CS0169
我正在尝试使用构造函数在 main 方法中创建一个 class 实例(我在上面的方法中删除了 static),但似乎无法弄清楚如何使用该实例激活它。请帮忙谢谢
这是我正在使用的代码,我截图了我得到的错误。
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();
}
}
}
在访问其非静态方法之前,您必须创建一个 Calculator
实例(并将 operand
值传递给构造函数)。从构造函数中删除 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);
我正在尝试使用构造函数在 main 方法中创建一个 class 实例(我在上面的方法中删除了 static),但似乎无法弄清楚如何使用该实例激活它。请帮忙谢谢
这是我正在使用的代码,我截图了我得到的错误。
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();
}
}
}
在访问其非静态方法之前,您必须创建一个 Calculator
实例(并将 operand
值传递给构造函数)。从构造函数中删除 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);