0

我正在使用 C# (WPF) 应用程序中的 RGB 颜色数据,发现自己有很多剪切和粘贴的代码

totals.red += currentPixel.red;
totals.green += currentPixel.green;
totals.blue += currentPixel.blue;

我想减少这种复制粘贴和复制粘贴错误的漏洞。我可以在这个地方使用大小为 3 的数组,但按数字访问这些数组会降低可读性。

我想写这样的东西:

for (col = all colours) {
  totals[col] += currentPixel[col];
}

我知道如何在 C 中解决这个问题,但我不熟悉 C#。有枚举的东西?

编辑:使示例更有意义。

4

3 回答 3

1

如果你真的想为此使用枚举,你可以这样做:

enum Color { red, green, blue };

{
    foreach (int colorValue in Enum.GetValues(typeof(Color)))
        thing[colorValue] = otherthing[colorValue] * 2;
}

这也将允许您在其他代码中按名称获取单个颜色:

var color = thing[Color.red];
于 2012-11-21T16:40:59.673 回答
0

假设红色、绿色和蓝色的类型为 Color

您可以设置颜色列表

List<Color> colors = new List<Color>();

向其中添加项目:

colors.Add(green);
colors.Add(blue);
colors.Add(red);

然后迭代:

foreach (Color color in colors)
{
    color.thing = color.otherThing * 2
}
于 2012-11-21T16:38:06.677 回答
0

枚举在这里无济于事。但是您可以像在整数数组或结构数组中那样定义自己的类型- 哪个更好?,并重载算术运算符,如http://msdn.microsoft.com/en-us/library/8edha89s(v=vs.80).aspx中所述,以允许乘以 int 例如。例如

thing = otherthing * 2;
于 2012-11-21T16:38:51.950 回答