在设置属性后创建类,如何测试属性并启用它?

时间:2012-05-03 06:58:40

标签: c# class properties

我知道这很简单,但我无法弄清楚。我正在创建一个类,我的函数是给我问题的。我正在使用O'Reilly的C#3.0作为参考。

我创建了一个类:

class Runner
{
    public double miles = 0;

    public double RunMiles
    {
        get { return miles; }
        set
        {
            if ((value > 2)&&(value <7))
            {
                this.miles = value;
            } 
        }
    }

    public void StartRun ()
    {      
        // here, I want to enable the runner to start running, Make him start running//if that makes any sense.
    }

    public void VerifyMiles ()
    {
        // enter code here//I want to verify the miles are set.
    }
}

1 个答案:

答案 0 :(得分:0)

对于OP的评论,一些基本的东西。

Runner r = new Runner(); //you created an instance of type Runner in memory now
int i = r.RunMile; //i is now 0 since variable miles is 0 initially, so RunMiles is also 0

r.RunMiles = 34;
i = r.RunMile; //i is still 0 since variable miles is not affected 'cos of your "if ((value > 2)&&(value <7))" in setter logic

r.RunMiles = 3;
i = r.RunMile; //i is 3 now

要开始跑步,你应该这样做:

r.StartRun();

并验证里程,

r.VerifyMiles();


public void StartRun ()
{     
    miles++; //your logic here
}

public void VerifyMiles ()
{
    if (miles > 26.22)
       //print successfully completed one round of marathon
    else
       //he died in the meanwhile :(..
}

这就是你在OOP中基本上做的事情