我试图使用" + ="增加" int Pos"在每次运行for循环时,Secondclass为1。但它的效果不如我在静态虚空主体中所做的那样好。
这是我的代码:
<maven.compiler.source>1.7</maven.compiler.source>
答案 0 :(得分:0)
您的代码完全符合预期 - 显示 Pos = 1 每次你进入。
如果您希望看到
Pos = 1
Pos = 2
Pos = 3
...
您应该对Firstclass和Main
进行以下更改学习c#祝你好运:)
public class Firstclass
{
int Pos = 1;
int Neg = 0;
Secondclass obj = new Secondclass(); // this should be here
public void Method1(string str)
{
if (Pos > Neg)
{
//Secondclass obj = new Secondclass(); -- you shouldn't create new object any time Method1 is called
obj.Pos += 1;
obj.Method2();
}
}
}
class Program
{
static void Main(string[] args)
{
Firstclass objj = new Firstclass(); // this should be here
for (; ; )
{
string e = Console.ReadLine();
//Firstclass objj = new Firstclass(); -- you shouldn't create new object on every iteration
objj.Method1(e);
}
}
}