优雅的方法来根据布尔值否定数值

时间:2011-08-01 17:29:26

标签: c#

我有一个十进制变量,如果布尔变量为真,我想否定它。任何人都可以想到比这更优雅的方式:

decimal amount = 500m;
bool negate = true;

amount *= (negate ? -1 : 1);

我正在考虑按位运算符或严格的数学实现。

7 个答案:

答案 0 :(得分:13)

就个人而言,我只会使用if语句,因为我觉得它在意图方面最明确:

decimal amount = 500m;
bool negate = true;

// ...

if (negate)
    amount *= -1;

这真的不是任何额外的打字(它实际上更短!),在我看来更清晰。

答案 1 :(得分:2)

使用十进制一元否定运算符(因为你已经在做了):

using System;

class Program
{
    static void Main()
    {
        bool negate = true;
        decimal test = 500M;
        Console.WriteLine(negate == true ? -test : test);
    }
}

输出:

-500

坦率地说,这比以这种奇怪的方式乘以-1更清晰,更好。

答案 2 :(得分:2)

数学巫师的另一个镜头?

如何调整现有解决方案以使其更具可读性,但仍然可以使用该语句?true:false shortcut?

您的解决方案是:

amount *= (negate ? -1 : 1);

也许重构到

amount = (negate ? amount*-1 : amount);

为了为代码添加更多可读性,您可以创建一个可重用的类来为您处理这类内容:

public static class MathHelpers()
{
  // Negates the result if shouldNegate is true, otherwise returns the same result
  public static decimal Negate(decimal value, bool shouldNegate)
  {
    // In this black-box solution you can use "fancier" shortcuts
    return value *= negate ? -1 : 1;
  }
}

在你的其他代码中,你现在有一个非常易读的功能......

decimal amount = 500m;
bool negate = true;
amount = MathHelper.Negate(amount, negate);

总而言之,虽然我同意优雅和可读性存在于同一个购物车中,而不是不同的:

if (condition)
  output *= -1;

更具可读性
value *= condition ? -1 : 1;

答案 3 :(得分:1)

public static decimal Negate(this decimal value, bool isNegate){
    if(isNegate) return value * -1;
    return value;
}

在十进制上进行扩展方法。易于使用。

调用amount.Negate(negate)

答案 4 :(得分:1)

这已经存在,因为框架1.1:

System.Decimal.Negate方法

public static decimal Negate( decimal d )

样本用法:

decimal amount = 500m;
bool negate = true;

if(negate)
    amount = decimal.Negate(amount);
// amount now holds -500
// Use amount

答案 5 :(得分:0)

如果您的negate标记基于某个数值,则可以使用Math.Sign,这是我能想到的最“数学”方式。

double negationValue = -45.0;
amount *= Math.Sign(negationValue);

或在布尔情况下(不是很优雅):

amount *= Math.Sign(0.5 - Convert.ToByte(negate));

答案 6 :(得分:-1)

amount *= Math.Pow(-1, Convert.ToInt32(negate))

这是假设在C#中对类型进行类型转换将在false时产生0,为true时产生1。然而,我不认为这是一种优雅,因为它是一种混淆。

编辑:转换为int