如何使用类方法来停止循环?

时间:2015-02-16 10:22:39

标签: c#

我上课了:

public class myclass {
  bool b;

  public bool notEnough {
    if (this.b) { return true; }
    else { return false;)
  }
}

尝试:

myclass obj = new myclass;
obj.b = true;
while (obj.notEnough) {
  Thread.Sleep(5);
}

出于某种原因,(obj.notEnough)中出现错误。怎么做对了?

2 个答案:

答案 0 :(得分:3)

您想要调用方法,因此您必须添加括号:

myclass obj = new myclass();
obj.b = true;
while (obj.notEnough()) { //Methods are always called by using the parenthesis ()
  Thread.Sleep(5);
}

答案 1 :(得分:3)

这会导致无限while循环。下面是编译后的代码

class Program
{
    static void Main(string[] args)
    {
        myclass obj = new myclass();
        obj.b = true;
        while (obj.notEnough())
        {
            Thread.Sleep(5);
        }
    }
}

public class myclass
{
    public bool b;

    public bool notEnough()
    {
        if (this.b)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}