简体   繁体   English

C#中的枚举数组索引

[英]enum array index in c#

I am working with RGB colour data in a C# (WPF) app, and find myself with a lot of cut and pasted code along the lines of 我正在C#(WPF)应用程序中处理RGB颜色数据,发现自己有很多剪切和粘贴的代码,包括

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

I'd like to reduce this copy-pasting and vulnerability to copy-paste errors. 我想减少这种复制粘贴和对复制粘贴错误的攻击。 I could use arrays of size 3 around the place, but accessing those by number reduces readability. 我可以在周围使用大小为3的数组,但是按数字访问这些数组会降低可读性。

I'd like to write something like this: 我想写这样的东西:

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

I'd know how to go about this in C, but am unfamiliar with C#. 我知道如何使用C进行此操作,但不熟悉C#。 Something with enums? 有枚举吗?

Edit: Made the example make more sense. 编辑:使该示例更有意义。

If you really want to use enums for this, you can do it this way: 如果您真的想为此使用枚举,则可以这样进行:

enum Color { red, green, blue };

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

This would also allow you to grab an individual color by name in other code: 这也将允许您在其他代码中按名称获取单个颜色:

var color = thing[Color.red];

Assuming that red, green and blue are of type Color 假设红色,绿色和蓝色为颜色类型

You can setup a List of colours 您可以设置颜色列表

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

Add items to it: 向其中添加项目:

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

Then itterate: 然后致死:

foreach (Color color in colors)
{
    color.thing = color.otherThing * 2
}

Enums won't help here. 枚举在这里无济于事。 But you can define your own type as done in Integer array or struct array - which is better? 但是您可以像在Integer数组或struct数组中定义的那样定义自己的类型-哪个更好? , and overload the arithmetic operators as described in http://msdn.microsoft.com/en-us/library/8edha89s(v=vs.80).aspx to allow multiplying to an int for example. ,并按http://msdn.microsoft.com/zh-cn/library/8edha89s(v=vs.80).aspx中所述重载算术运算符,以允许乘以一个int。 Eg 例如

thing = otherthing * 2;

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

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