C#设置Int或Float的最大/最小返回值

时间:2013-11-07 00:22:54

标签: c# math accessor

我希望控制值的输出始终低于(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数组值)这成了一个轻微的瓶颈

2 个答案:

答案 0 :(得分:3)

现在你正在做两次加法。我会这样做:

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

事后看来,这段代码的清洁版本是:

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

        return newSpeed;
}

答案 1 :(得分:1)

public int Speed
{
  get
  {
     return CurrentSpeed + CarAcceleration;
  {
}

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

        return Speed;
    }
    set;
    }

我猜你可以汇总计算以避免在多个地方重复汇总。

我建议避免过早优化。根据您的示例,似乎性能不会成为一个问题。你真的看到了性能问题吗?