选择条件下的数学运算

时间:2011-12-21 13:18:28

标签: c# .net math

我可能有一个奇怪的问题,但我会尝试描述它。 我有一个带有两个数学运算“%”和“/”的表达式:

int a = x / y;
int a = x % y;

我有一个函数的参数,我检查,我必须为这个表达式实现什么Math运算符(%或/)。因此,有一种方法可以选择运算符表达式而无需重复代码

int a = parameter ? x / y: x % y;

if (parameter) a = x/y; else a = x%y;

这对我来说是错的。

有一种方法可以使用这样的东西:

int a = x (parameter ? / : %) y;

代码愿景问题:

items.Where((item, index) => 
                    settings.cbl_Direction == Direction.Horizontal ?
                        index / (int)settings.cbl_RepeatColumns == i 
                    :
                        index % (int)settings.cbl_RepeatColumns == i)

4 个答案:

答案 0 :(得分:5)

你可以这样做:

Func<int, int, int> div = (m, n) => m / n;
Func<int, int, int> mod = (m, n) => m % n;

int a = (parameter ? div : mod)(x, y);

在我看来,这会稍微增加代码的复杂性,所以坚持使用已有的东西可能会更好。

答案 1 :(得分:0)

我认为你的方法是正确的,因为没有任何方法来写这个,我也没有看到任何其他方式。所以使用这两种方式,

int a = parameter ? x / y: x % y;

if (parameter) a = x/y; else a = x%y;

这两种方法很好,足以减少代码......

答案 2 :(得分:0)

只需使用

if (parameter) a = x/y; else a = x%y; 

除非你有一个非常令人信服的理由不这样做,否则你只是在没有充分理由的情况下引入复杂性。 软件很复杂,没有引入不必要的复杂性。

答案 3 :(得分:0)

这可能不是最好的解决方案,但我花时间编写代码,所以我也可以发布它:

定义这两个:

private const string ClassString1 =
        @"
    namespace MyNamespace
    {
        public static class MyClass
        {
            public static int InvokeMath(int x, int y)
            {
                return ";
    private const string ClassString2 = @";
            }
        }
    }";

实现魔法的方法:

public static int MethodOperation(int x, int y, string @operator)
    {
        var sharpCom = new CSharpCodeProvider();
        var results = sharpCom.CompileAssemblyFromSource(new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false }, ClassString1 + string.Format("x {0} y", @operator) + ClassString2);
        return (int)results.CompiledAssembly.GetTypes().First().GetMethods().First().Invoke(null, new object[] { x, y });
    }

像这样使用:

var divide = MethodOperation(2, 2, "/");
var mod = MethodOperation(2, 2, "%");

重复使用代码,同时牺牲可读性,速度以及您可以牺牲的所有其他内容!