无法使用实例引用访问
本文关键字:引用 访问 实例 | 更新日期: 2023-09-27 17:50:30
我仍然在我的编程任务中间,试图使用方法来制作计算器,我得到:
Member 'LabAssignFiveCalc.Sum.Addition(double, double)' cannot be accessed with an instance reference; qualify it with a type name instead
在这行代码
Sum s = new Sum();
if (metUse == "Addition")
result = s.Addition(num1, num2);
整个文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LabAssignFiveCalc
{
public class Sum
{
//Addition method
public static double Addition(double num1, double num2)
{
double result;
result = num1 + num2;
return result;
}
//Subtraction method
public static double Subtract(double num1, double num2)
{
double result;
result = num1 - num2;
return result;
}
//Multiplication method
public static double Multiply(double num1, double num2)
{
double result;
result = num1 * num2;
return result;
}
//Division method
public static double Divide(double num1, double num2)
{
double result;
result = num1 / num2;
return result;
}
}
public class Program
{
//Main
static void Main(string[] args)
{
//Declare Variables
int choice;
string op;
double num1;
double num2;
double result;
string metUse;
//Ask user for calculation parameters
Console.WriteLine("Calculator:");
Console.WriteLine("Which operation do you wish to perform? Type the corresponding number.");
Console.WriteLine("1) Addition'n2) Subration'n3) Multiplication'n4) Division");
choice = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please type the first number you wish to calculate");
num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please type the second number you wish to calculate");
num2 = Convert.ToDouble(Console.ReadLine());
//Declare Operator
switch (choice)
{
case 1:
op = "+";
metUse = "Addition";
break;
case 2:
op = "-";
metUse = "Subtract";
break;
case 3:
op = "*";
metUse = "Multiply";
break;
case 4:
op = "/";
metUse = "Divide";
break;
default:
throw new ArgumentException();
}
Sum s = new Sum();
if (metUse == "Addition")
result = s.Addition(num1, num2);
//Show Calculation
Console.WriteLine("{0}{1}{2}={3}", num1, op, num2, result);
Console.ReadKey();
}
}
}
就像我说的,我还是个初学者,所以请对我宽容一点:p这可能是一些真正的新手错误。
Thanks for the help:D
Addition
是一个静态方法。
不能使用类型的实例调用静态方法;用类型本身调用。
试试这个:
if (metUse == "Addition")
result = Sum.Addition(num1, num2);
Sum类的Addition成员被标记为静态。这意味着它不能在实例化的类上调用。这样做:
result = Sum.Addition(num1, num2);
由于addition是Sum类中的静态方法,因此可以通过Sum .addition(a,b);你不需要创建一个对象来使用它