C# 比较简写

发布于 2024-10-12 05:21:17 字数 471 浏览 12 评论 0原文

我有这段代码:

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

是否有某种形式的速记形式,以便我可以将其重写为这样的代码?

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

功能应该完全相同。我只是在寻找一些看起来不那么混乱的东西。

编辑抱歉没有澄清,所有变量都是整数。我正在寻找一种更短的方法来确保 a, b, c, d, ...全部等于y

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

风透绣罗衣 2024-10-19 05:21:17

您将获得的最接近的结果(无需实现您自己的机制):

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

The closest you're going to get (without implementing your own kind of mechanism):

if (new[] { a, b, c, d }.All(value => y == value))
    // ...
小梨窩很甜 2024-10-19 05:21:17

,没有任何东西可以简化您的代码,同时又不会以巨大的性能损失来抵消可读性的好处。


编辑:高性能解决方案

如果您非常渴望尝试高性能解决方案,这里有一个:(

更新:显然我错误地认为您可以将泛型与可变参数一起使用;您显然只能因此,我将下面的类型更改为 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;
}

然后尝试使用以下命令调用它:

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

警告:人们可能会因为这样做而对你大喊大叫,所以请使用风险由您自行承担。 :)

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.)

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. :)

霓裳挽歌倾城醉 2024-10-19 05:21:17

稍微更具可读性(在我看来)是:

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

但我不相信基本语言中有任何东西可以实现这一点。

如果您确实想要像您所建议的那样,那么这就是函数的用途,例如:

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

但您可能需要在性能方面小心。


如果这是在 a/b/c/d/... 不变的循环中完成的,那么一件事可能对您有用(换句话说,只有y 正在改变)。

检查循环外不变量的相等性:

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

因为,如果情况并非如此,则 y 永远不可能等于所有这些不变量。然后,在循环内部,只需执行以下

if (y == a)

操作:您已经知道所有非 y 变量彼此相等,这意味着您只需检查 y 即可其中之一。

但是,由于我还没有看到你的完整代码,我不确定它是否对你有用。


我应该提到,虽然很冗长,但原始代码实际上没有什么不可读的,特别是如果它的格式很好的话。即使是庞然大物:

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))
{
    ...
}

也是可读的(尽管我不太喜欢简洁的变量名)。

当然,此时,您可能想要考虑使用带有循环的数组而不是单一变量。

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).

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. 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.

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.

软糯酥胸 2024-10-19 05:21:17

不,没有。坚持你所拥有的。

好吧,您可以编写一个 public static bool AllEqual(params T[] value) (也许可以重载 2/3/4/5 操作数以避免数组创建),但我'大多数时候我不确定这是否值得。

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.

变身佩奇 2024-10-19 05:21:17

试试这个:

假设您正在比较字符串

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

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
悸初 2024-10-19 05:21:17

尽管无法确定,但我会查看您的整体代码结构,看看是否有更好的方法来处理整个区域。

每当你有一个这样重复的模式时,你可能需要对其进行大量修改。您最终可能需要添加新的 q==y 或更改某些内容。

这里很多人都关心性能,但更重要的是确保您的代码可维护、可理解且经过正确分解。

作为一个总的猜测,我想说你的 a,b,c,d 变量应该都是 4 个不同对象的成员,ax, bx, cx, dx a,b,c,d 代表什么?它们不能只是任意数字,它们是价格或像素位置或元素的权重——某种东西!我无法想象一种情况,你会恰好有 4 个,而不是 5 个或 3 个。

不管怎样,无论它代表什么,可能还有其他与之相关的东西——名称、大小、颜色、控制索引——等等。

一般来说,我会寻求更高级别的解决方案来解决这个问题。我想说至少 a、b、c 和d 应该是在程序外部定义的内容,无论是在数据文件还是数据库中。

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.

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, a.x, b.x, c.x, d.x. what do a,b,c,d represent? 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.

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.

青柠芒果 2024-10-19 05:21:17
new[] { a, b, c, d }.Contains(y)
new[] { a, b, c, d }.Contains(y)
高跟鞋的旋律 2024-10-19 05:21:17

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


if ( y == a == b == c == d)
{
//这里代码
}

对于 if (y == a || y == b || y == c || y == d) 并且 y 是简单类型或字符串,请使用:

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

}

For if (y == a && y == b && y == c && y == d), use:


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:

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

}
你是暖光i 2024-10-19 05:21:17
   bool  x=true ,y=true, z=true, p = true;

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

    x = false;
    if (x == (y == z == p)) //false
   bool  x=true ,y=true, z=true, p = true;

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

    x = false;
    if (x == (y == z == p)) //false
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文