我有一个十进制变量,如果布尔变量为真,我想将其求反。有没有人能想到比这更优雅的方式呢:
decimal amount = 500m;
bool negate = true;
amount *= (negate ? -1 : 1);我在考虑一些类似于按位运算符或严格数学实现的东西。
发布于 2011-08-02 01:32:03
就我个人而言,我只会使用if语句,因为我觉得这是最明确的意图:
decimal amount = 500m;
bool negate = true;
// ...
if (negate)
amount *= -1;这真的不是任何额外的输入(它实际上更短!),在我看来更清楚。
发布于 2011-08-02 01:59:14
使用十进制一元求反运算符(就像你已经在做的那样):
using System;
class Program
{
static void Main()
{
bool negate = true;
decimal test = 500M;
Console.WriteLine(negate == true ? -test : test);
}
}输出:
-500坦率地说,这比以那种奇怪的方式乘以-1要清楚得多,也好得多。
发布于 2011-08-02 03:09:09
又一次穿越数学奇才的机会?
如何调整现有的解决方案,使其更具可读性,但仍然使用语句?true:false快捷方式?
您的解决方案是:
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;https://stackoverflow.com/questions/6902103
复制相似问题