我是C#的新学员,而且我上课时遇到了困难。特别是在尝试使用对象时。我一直试图制作一个计算器,并因错误而被迫缩短。我试图自己解决这个问题,但在尝试修复之后我似乎更加困惑。
我试图创建一个用户输入两个数字的应用程序,它使用一个类对象来计算它们并将它带回main方法。如果经常被问到,请道歉。并提前谢谢你。
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int num1;
//ask user for number
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter a second number");
int num2;
//ask user for number
num2 = int.Parse(Console.ReadLine());
//initialize class object
Addition addi = new Addition();
Console.WriteLine("The answer of both {0} and {1} is {2}", num1, num2, addi);
Console.ReadLine();
}
}
这是将进行添加并将其传递给main方法的类。
class Addition
{
public static void Add(int x, int y)
{
x;
y;
int ans;
ans = x + y;
//get an error "Since 'Addition.add' returns void, a return keyword must not be followed by an object expression "
return ans;
}
}
答案 0 :(得分:0)
这个类有两种工作方式......静态或实例化。
如果你想让main方法以这种方式工作......
Addition addi = new Addition();
Console.WriteLine("The answer of both {0} and {1} is {2}", num1, num2, addi);
然后你的Addition类应该更像这样:
class Addition
(
private readonly int result;
public Addition(int num1, int num2)
{
result = num1 + num2;
}
public override string ToString()
{
return result.ToString();
}
}
然后它会稍作改动:
Addition addi = new Addition(num1, num2); //Have to pass the values in
Console.WriteLine("The answer of both {0} and {1} is {2}", num1, num2, addi);
静态方法不需要实例,因此您必须更改此内容:
Addition addi = new Addition();
Console.WriteLine("The answer of both {0} and {1} is {2}", num1, num2, addi);
对此:
var addi = Addition.Add(num1, num2);
Console.WriteLine("The answer of both {0} and {1} is {2}", num1, num2, addi);
你的班级应该是这样的:
static class Addition
{
static public int Add(int num1, int num2)
{
return num1 + num2;
}
}