所以我在使用setter和getter时遇到了麻烦,我想我现在无法获得addNumbers的值,我已经将其他人注释掉了,所以我现在并不担心它们。一旦我将addnumbers传递给setter,从getter中检索if然后在addNumbers中使用它,我最关心的是写入addnumbers值所需的语法。如果有人能够启发我或给我一个体面的例子,那将比我现在更好。非常感谢您的帮助!
class MainModule
{
static void Main(string[] args)
{
Info myInfo = new Info();
myInfo.DisplayInfo("Assignment 3A - Math Ops w/ Properties");
MathOperations ops = new MathOperations();
int input1, input2;
Console.WriteLine("Enter first number to calculate");
ops.operand1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter second number to calculate");
ops.operand2 = int.Parse(Console.ReadLine());
Console.WriteLine("Added: {0}", ops.addNumbers);
//Console.WriteLine("Subtracted: " + ops.subtractNumbers(value1, value2));
//Console.WriteLine("Divided: " + ops.divideNumbers(value1, value2));
//Console.WriteLine("Multiplied: " + ops.multiplyNumbers(value1, value2));
Console.ReadLine();
}
class MathOperations
{
private int operand1;
private int operand2;
public int Operand1
{
get
{
return operand1;
}
set
{
operand1 = value;
}
}
public int Operand2
{
get
{
return operand2;
}
set
{
operand2 = value;
}
}
public MathOperations()
{
//default constructor
}
public MathOperations(int op1, int op2)
{
operand1 = op1;
operand2 = op2;
}
public int addNumbers()
{
return operand1 + operand2;
}
答案 0 :(得分:1)
addNumbers
不是上面定义的属性。这是一种方法,您需要添加parenthesys
Console.WriteLine("Added: {0}", ops.addNumbers());
.....
public int addNumbers()
{
return operand1 + operand2;
}
否则,但我不推荐它,因为您正在执行不读取类的属性的操作,将代码更改为
Console.WriteLine("Added: {0}", ops.addNumbers);
.....
public int addNumbers
{
get{ return operand1 + operand2; }
}
以这种方式,你有一个getter属性为你的getter。但是我仍然认为属性应该表示类的属性而不是操作,因此在这种情况下,实现方法似乎更正确。