开发者

Passing two different property values to a method

开发者 https://www.devze.com 2023-03-29 12:49 出处:网络
I have two different properties and hence two values.These properties are read and write properties.I have one method and I need to pass both property values to this one method.How to I accomplish thi

I have two different properties and hence two values. These properties are read and write properties. I have one method and I need to pass both property values to this one method. How to I accomplish this? Is using Array the only way 开发者_开发知识库to do this? Here is example:

In a Calculator example:

//Property 1
public int numberone
{
 get { return passnumberone; }
 set { passnumberone = Add(value);}
}
//Property 2
public int numbertwo
{
 get { return passnumbertwo; }
 set { passnumbertwo = Add(value);}
 }
//Method
private int Add(?)
{
int numberone
int numbertwo
int finalanswer
finalanswer = numberone + numbertwo
return finalanswer;
}
//Calling 
Calculator.numberone = 10;
Calculator.numbertwo = 12;

I know I could use the method only and pass these two number very easily. But I am trying to use the porperties.

Thanks in Advance!


You will have to pass the object that contains the properties to the method if the object is not the same as the one that contains the Add method.

class CalculatorInputs
{
  public int numberone;
  public int numbertwo;
}

class CalculatorOperations
{
  public int Add(CalculatorInputs input)
  {
    return input.numberone + input.numbertwo;
  }

}


You can pass both values to the method as parameters:

private int Add(int numberone, int numbertwo)
{
    int finalanswer
    finalanswer = numberone + numbertwo
    return finalanswer;
}

Then you would call it like this:

int answer = this.Add(numberone, numbertwo);

But to be honest your first question contradicts your second, also, you shouldn't be calling this everytime you set a number, seems kind of confusing to me, and there's probably a better way to do it, but I'm insure of what you're trying to achieve.


Since you are setting the properties beforehand calling the method, you don't have to pass anything to the method.

private int Add()
{
    int finalanswer;
    finalanswer = this.numberone + this.numbertwo
    return finalanswer;
}

and you can call

Calculator c = new Calculator();
c.numberOne = 10;
c.numberTwo = 12;
int sum = c.Add();


I am not sure what you are upto here but in any case you would be needing a Third property which will actually give you the Added value;

So need of calling the Add method at all

public int AddedNumber
{
 get { return passnumberone + passnumbertwo ; } 
}

If this is not what you intend then please expand and add more details to your question.

0

精彩评论

暂无评论...
验证码 换一张
取 消