简体   繁体   English

C#比较速记

[英]C# Comparison shorthand

I have this code: 我有这个代码:

    if (y == a && y == b && y == c && y == d ...)
    {
        ...
    }

Is there some form of shorthand so that I can rewrite it as something like this? 是否有某种形式的速记,以便我可以像这样重写它?

    if(y == (a && b && c && d ...))
    {
        ...
    }

The functionality should be exactly the same. 功能应该完全相同。 I'm just looking for something that looks less confusing. 我只是在找一些看起来不那么混乱的东西。

EDIT Sorry for not clarifying, all the variables are integers. 编辑很抱歉没有澄清,所有变量都是整数。 I'm looking for a shorter way to ensure that a , b , c , d , ... all equal y . 我正在寻找一种更短的方法来确保abcd ,......都等于y

The closest you're going to get (without implementing your own kind of mechanism): 你最接近的(没有实现你自己的机制):

if (new[] { a, b, c, d }.All(value => y == value))
    // ...

No , there isn't anything that will simplify your code without outweighing the readability benefits with a big performance penalty. ,没有什么可以简化您的代码而不会超过可读性优势而导致性能损失很大。


Edit: High-performance solution 编辑: 高性能解决方案

If you're desperate enough to try a high-performance solution, here's one: 如果您非常渴望尝试高性能解决方案,请参阅以下内容:

(Update: Apparently I was wrong in thinking you can use generics with varargs; you apparently can only hard-code the types. So I changed the type below to int instead, but the same code applies.) (更新:显然我认为你可以在varargs中使用泛型;我显然只能对类型进行硬编码。所以我将下面的类型更改为int ,但是相同的代码适用。)

static bool AllEqual(int value, __arglist)
{
    for (var ai = new ArgIterator(__arglist); ai.GetRemainingCount() > 0; )
    {
        var next = __refvalue(ai.GetNextArg(typeof(int).TypeHandle), int);
        if (!value.Equals(next)) { return false; }
    }
    return true;
}

Then try calling it with: 然后尝试调用它:

//...
bool equal = AllEqual(1, __arglist(1, 1, 1));

Warning: People will probably yell at you for doing this, so use it at your own risk. 警告:人们可能会因为这样做而对你大喊大叫,所以使用它需要你自担风险。 :) :)

Slightly more readable (in my opinion) is: 稍微更具可读性(在我看来)是:

if ((y == a) && (y == b) && (y == c) && (y == d) ...)

but I don't believe there's anything in the base language for this. 但是我不相信基础语言中有任何东西。

If you really want something like what you propose, that's what functions are for, something like: 如果你真的想要你所建议的东西,这就是函数的用途,例如:

if (isSetToAll (y, a, b, c, d, ...))

but you might want to be careful on the performance front. 但你可能要在性能方面小心谨慎。


One thing may be of use to you if that's being done in a loop where a/b/c/d/... are invariant (in other words, where only y is changing). 如果在a/b/c/d/...不变的循环中完成(换句话说,只有y在变化的情况下),有一件事可能对你有用。

Check the equality for the invariants outside the loop: 检查循环外不变量的相等性:

if ((a == b) && (a == c) && (a == d) ...)

because, if that's not the case, then y can never be equal to all of them. 因为,如果不是这样,那么y永远不会等于所有这些。 Then, inside the loop, just do: 然后,在循环内部,只需:

if (y == a)

The fact that you already know that all the non- y variables are equal to each other means that you only need to check y against one of them. 事实上,你已经知道,所有的非y变量彼此相等,意味着你只需要检查y对他们中的一个。

But, since I haven't seen your complete code, I'm not sure if it will be useful to you. 但是,由于我没有看到您的完整代码,我不确定它是否对您有用。


I should mention that, while verbose, there's nothing actually unreadable about your original code, especially if it's formatted nicely. 我应该提一下,虽然详细,但你的原始代码实际上并不可读,特别是如果它的格式很好。 Even the behemoth: 即使是庞然大物:

if ((y == a) && (y == b) && (y == c) && (y == d) &&
    (y == e) && (y == f) && (y == g) && (y == h) &&
    (y == i) && (y == j) && (y == k) && (y == l) &&
    (y == m) && (y == n) && (y == o) && (y == p) &&
    (y == q) && (y == r) && (y == s) && (y == t) &&
    (y == u) && (y == v) && (y == w) && (y == x))
{
    ...
}

is readable (though I'm not a big fan of terse variable names). 是可读的(虽然我不是简洁变量名的忠实粉丝)。

Of course, at that point, you may want to look into using arrays with loops rather than singular variables. 当然,在这一点上,您可能希望研究使用带循环的数组而不是奇异变量。

No, there isn't. 不,没有。 Stick with what you have. 坚持你所拥有的。

Well, you could write a public static bool AllEqual<T>(params T[] values) (maybe with overloads for 2/3/4/5 operands to avoid the array creation), but I'm not sure it is worth it most times. 好吧,你可以写一个public static bool AllEqual<T>(params T[] values) (可能有2/3/4/5操作数的重载以避免数组创建),但我不确定它是否值得大部分时间。

Try this: 尝试这个:

Assuming you're comparing strings 假设你正在比较字符串

IList<string> valuesToCompare = new List<string> { "a", "b", "c", "d" };

if (valuesToCompare.Any(valueToCompare => valueToCompare != y)) 
       //If there is any value that is not equal to y
       //Do something
new[] { a, b, c, d }.Contains(y)

Although it's impossible to be sure, I'd look at your overall code structure and see if there isn't just a better way to handle that whole area. 虽然不可能确定,但​​我会查看您的整体代码结构,看看是否有更好的方法来处理整个区域。

Any time you have a pattern that repeats like that, you will probably have to modify it a lot. 每当你有一个像那样重复的模式时,你可能需要对它进行很多修改。 Chances are that you will need to add a new q==y or change something eventually. 您可能需要添加新的q == y或最终更改某些内容。

A lot of people here were concerned with performance, but it's much more important to make sure your code is maintainable and understandable and properly factored. 这里很多人都关心性能,但确保你的代码可维护,易懂和适当考虑因素更为重要。

As a total guess, I'd say that your a,b,c,d variables should all be a member of 4 different objects, ax, bx, cx, dx what do a,b,c,d represent? 作为总猜测,我会说你的a,b,c,d变量都应该是4个不同对象的成员,ax,bx,cx,dx a,b,c,d代表什么? They can't just be arbitrary numbers, they are prices or pixel locations or weights of elements--something! 它们不能只是任意数字,它们是价格或像素位置或元素的权重 - 一些东西! I can't imagine a condition where you'd have exactly 4 and never 5 or 3 of something. 我无法想象你有4个而且从不5或3个东西的情况。

Anyway, whatever it represents, there are probably other things associated with it--a name, size, color, control index--whatever. 无论如何,无论它代表什么,可能还有其他与之相关的东西 - 名称,大小,颜色,控制指数 - 无论如何。

In general I'd look at a higher level for a fix to this problem. 一般来说,我会看一个更高级别来解决这个问题。 I'd say at least a,b,c & d should be something defined outside the program, either in a data file or database. 我要说至少a,b,c&d应该是在程序之外定义的东西,无论是在数据文件还是数据库中。

For if (y == a && y == b && y == c && y == d) , use: 对于if(y == a && y == b && y == c && y == d) ,请使用:

if ( y == a == b == c == d) { //code here } if(y == a == b == c == d){// code here}

For if (y == a || y == b || y == c || y == d) and y is a simple type or string, use: 对于if(y == a || y == b || y == c || y == d)且y是简单类型或字符串,请使用:

switch(y)
{
   case a:
   case b:
   case c:
   case d:
     //your code here
     break;

}
   bool  x=true ,y=true, z=true, p = true;

    if (x == (y == z == p)) //true

    x = false;
    if (x == (y == z == p)) //false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM