更改矩形列表中矩形的x值 [英] Change x value of rectangle in rectangle list

查看:94
本文介绍了更改矩形列表中矩形的x值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单应用程序中创建了一个矩形列表,需要在此列表中创建一个矩形移动。这是我的代码:



 List< Rectangle> squares = new List< Rectangle>(); 

//假设我做了一个名为r
squares.Add(r)的任意矩形;

//这是我需要做的事情
for(int i = 0; i< squares.Count; i ++){

//问题在这里
square [i] .X + = 5;

}





我收到错误消息,说它无法修改返回值,因为它不是变量。我明白了,但我需要知道是否有办法绕过这个或其他方式来做到这一点。请帮忙。谢谢。

解决方案

可变值类型(struct)的字段,如Rectangle,如果它们在通用列表中,则不能直接赋值给它们。



虽然你可以使用'Offset方法没有错误,如果你使用一般的矩形列表,访问矩形将返回它的副本,'偏移运算符将处理该副本,使列表中的矩形保持不变。



解决方案是使用数组结构来保存矩形:

  private  Rectangle [] rList =  new 矩形[ 25 ]; 

private void MakeRects()
{
for int i = 0 ; i < 5 ; i ++)
{
for int j = 0 ; j < 5 ; j ++)
{
Rectangle r = new 矩形(i * 50,j * 50, 100 100 );
rList [(i * 5)+ j] = r;
}
}

rList [ 2 ]。偏移量( 1000 1000 );
rList [ 3 ]。Y + = 4000 ;
// 在这里设置一个断点:检查rList [2],rList的X和Y值[ 3]
}

如果你必须使用一个矩形列表,你别无选择,只能创建一个新的矩形,然后插入它代替原始的矩形。 / blockquote>

等我发现了,我只需要创建一个新的矩形,更改值,然后用新的矩形替换原始的矩形。


I made a rectangle list in a forms application and need to make a rectangle in this list move. Here is my code:

List<Rectangle> squares = new List<Rectangle>();

// Assume I have made some arbitrary rectangle named r
squares.Add(r);

// Here is what I need to do
for (int i = 0; i < squares.Count; i++) {

    // Problem Here
    squares[i].X += 5;

}



I get an error saying that it cannot modify the return value because it's not a variable. I get it but I need to know if there is a way to get around this or another way to do this. Please help. Thanks.

解决方案

Fields of a mutable value-type (struct), like a Rectangle, are, by design, not assignable to directly if they are in a Generic List.

While you can use the 'Offset method without error, if you use a generic List of Rectangles, accessing the Rectangle will return a copy of it, and the 'Offset operator will work on that copy, leaving the Rectangle in the List unchanged.

A solution is to use an Array structure to hold your Rectangles:

private Rectangle[] rList = new Rectangle[25];

private void MakeRects()
{
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 5; j++)
        {
            Rectangle r = new Rectangle(i*50, j*50, 100, 100);
            rList[(i*5) + j] = r;
        }
    }

    rList[2].Offset(1000, 1000);
    rList[3].Y += 4000;
    // put a break-point here: examine X and Y values of rList[2], rList[3]
}

If you have to use a List of Rectangles, you have no choice but to create a new Rectangle and then insert it in place of the original one.


Wait I figured it out, I just needed to create a new rectangle, change the values, then replace the original rectangle with the new one.


这篇关于更改矩形列表中矩形的x值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆