简体   繁体   English

在一行中更改多个变量?

[英]Change more then one variable in one line?

Lets say I have this 可以说我有这个

int x = 0;
int y = 0;
int z = 0;
const int v = 50;

//change x,y,z
x += v;
y += v;
z += v;

Its fine, but is there a shorter way to avoid this 3 lines of code (with += ) and have only one? 很好,但是有没有一种较短的方法来避免这三行代码(带有+= )并且只有一行? I just asking myself, because I have to add some const to these variables very often and then I have to add always +3 lines (or more if I would have xyz+ variables). 我只是问自己,因为我必须经常向这些变量添加一些const,然后我必须总是添加+3行(如果我有xyz +变量,则必须添加更多行)。

If this is going to happen very often, you might want to put these in a class. 如果这种情况经常发生,您可能需要将它们放在一个类中。 For example, if these are locations within a virtual page: 例如,如果这些是虚拟页面中的位置:

class PageLoc
{
    public int Header { get; set; }
    public int Body { get; set; }
    public int Footer { get; set; }

    void MoveAll(int distance) {
        Header += distance;
        Body += distance;
        Footer += distance;
    }
}

That way, you can change their values independently or collectively. 这样,您可以独立或集体更改其值。

You could define a method to increment all three variables and pass the variables by reference: 您可以定义一个方法来增加所有三个变量并通过引用传递变量:

Add(ref x, ref y, ref z, 50);

with

void Add(ref int x, ref int y, ref int z, int v)
{
    x += v;
    y += v;
    z += v;
}

Wrap the x,y,z into a class and write a method to add a constant to all three: 将x,y,z包装到一个类中,并编写一个为所有三个添加常量的方法:

class XYZ
{
  public void Add (int v) { x += v; y += v; z += v; }
  int x,y,x;
}

Some code to use above: 上面要使用的一些代码:

void F ()
{
  XYZ xyz;

  xyz.Add (3);
}

Of course, you can improve the above by overloading the += operator as well as the other operators. 当然,您可以通过重载+ =运算符和其他运算符来改进上述内容。 In effect, you've created a vector and there's libraries available that already implement this (maybe in DirectX). 实际上,您已经创建了一个矢量,并且已经有可用的库实现了该矢量(也许在DirectX中)。

z += 0 * (y += 0 * (x += v) + v) + v;

Tadah :D 他达:D

But I don't recommend using this! 但我不建议使用此功能! Of course the better way is to create a method that does that. 当然,更好的方法是创建一个执行该操作的方法。 That would also give you only one line (+ a method declaration). 那也只会给你一行(+方法声明)。

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

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