0

我知道这很简单,但我就是想不通。我正在创建一个类,我的功能是给我带来问题的原因。我使用 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.
    }
}
4

1 回答 1

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 中基本做事的方式

于 2012-05-03T23:55:23.870 回答