0

我希望控制值的输出始终低于(X)每次调用参数::

小例子~

public int CurrentSpeed;
public int MaxSpeed;
private int caracceleration;
private int Blarg;

public int CarAcceleration{
    get{ 
        Blarg = CurrentSpeed + caracceleration;
        if(Blarg >= MaxSpeed){
            Blarg = MaxSpeed
        }

        return Blarg

    set;
    }

有没有更好的方法来做到这一点而无需每次都调用参数?可悲的是,随着数字的数量和复杂性的增加(我在我的代码中使用 3d 值数组),这成为了一个轻微的瓶颈

4

2 回答 2

3

Right now you're doing the addition twice. I would do this:

get{ 
        var newSpeed = CurrentSpeed + CarAcceleration;
        if( newSpeed >= MaxSpeed){
            return MaxSpeed;
        }
        else{
            return newSpeed;
        }
}

In hindsight, a cleaner version of this code would be:

get{ 
        var newSpeed = CurrentSpeed + CarAcceleration;
        if( newSpeed >= MaxSpeed){
            newSpeed = MaxSpeed;
        }

        return newSpeed;
}
于 2013-11-07T00:27:13.277 回答
1
public int Speed
{
  get
  {
     return CurrentSpeed + CarAcceleration;
  {
}

public int CarAcceleration{
    get
    { 
        if(Speed >= MaxSpeed)
        {
            return MaxSpeed
        }

        return Speed;
    }
    set;
    }

I guess you can roll up the calculations to avoid repeating the summations in multiple places.

I recommend avoiding premature optimization. Based on your example it doesn't seem like performance will be much of an issue. Are you actually seeing performance problems?

于 2013-11-07T00:27:52.987 回答