[英]enum array index in c#
我正在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#。 有枚举吗?
编辑:使该示例更有意义。
如果您真的想为此使用枚举,则可以这样进行:
enum Color { red, green, blue };
{
foreach (int colorValue in Enum.GetValues(typeof(Color)))
thing[colorValue] = otherthing[colorValue] * 2;
}
这也将允许您在其他代码中按名称获取单个颜色:
var color = thing[Color.red];
假设红色,绿色和蓝色为颜色类型
您可以设置颜色列表
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
}
枚举在这里无济于事。 但是您可以像在Integer数组或struct数组中定义的那样定义自己的类型-哪个更好? ,并按http://msdn.microsoft.com/zh-cn/library/8edha89s(v=vs.80).aspx中所述重载算术运算符,以允许乘以一个int。 例如
thing = otherthing * 2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.