第一种方法:
public List<string> MembershipIds { get;set; }
...
// This constructor will do the assignment.
// If you do not plan to publish no-argument constructor,
// it's OK to make it private.
public MyClass() {
MembershipIds = new List<string>();
}
// All other constructors will call the no-arg constructor
public MyClass(int arg) : this() {// Call the no-arg constructor
.. // do other things
}
public MyClass(string arg) : this() {// Call the no-arg constructor
.. // do other things
}
第二种方法:
public void Calculate (int a, int b) {
int sum =a+b;
}
答案 0 :(得分:5)
目前还不完全清楚你想做什么,但看起来你有两种选择......
您可以将值存储在类级变量中:
private int sum = 0;
public void Calculate (int a, int b) {
sum = a + b;
}
public int getResult() {
return sum;
}
或者,可能更有效,只需从计算它的函数返回值:
public int Calculate (int a, int b) {
return a + b;
}
除非有其他特别好的理由,否则通常最好做最简单的事情。在这种情况下,只是添加数字并返回结果。否则,消耗代码需要记住在调用Calculate()
之前始终调用getResult()
,并且在使用对象时将创建对操作顺序的依赖。
答案 1 :(得分:4)
1. public int Calculate (int a, int b) {
int sum = a + b;
return sum;
}
2.
public int getResult(){
return sum = Calculate(15,12);
}
或试试这个 1. public int Calculate(int a,int b){ int sum = a + b; 回报; }
2.public int getResult(int a, int b){
return sum =Calculate(a,b);
}
答案 2 :(得分:3)
你的变量被loacalized只计算。你可以自己调用calulate或者在我的oppinon中调用全局化的可变
Class calculate {
int sum;
public void calculate(int a, int b) {
sum =a+b;
}
public int getResult(){
return sum ;
}
}
答案 3 :(得分:3)
class xyz {
int sum;
public void Calculate(int a, int b) {
sum = a + b;
}
public int getResult() {
return sum;
}
}