遍历所有颜色? [英] Loop through all colors?
问题描述
我正在使用C#(Windows-Phone-7)开发一个应用程序,并且正在尝试做一些让我感到困惑的简单事情.
I'm working on an app in C# (Windows-Phone-7), and I'm trying to do something simple that has me stumped.
我想循环显示每种颜色,并将颜色名称写到文件中(以及其他内容).
I want to cycle through each Color in Colors, and write out the Color name to a file (along with other stuff).
我有最简单的代码,虽然我知道这是行不通的,但是我还是写了入门书:
I have the simplest bit of code, which I know will not work, but I wrote to get started:
foreach (Color myColor in Colors)
{
}
当然,这给了我以下语法错误:
Of course, this gives me the following syntax error:
"System.Windows.Media.Colors"是类型",但其用法类似于变量".
'System.Windows.Media.Colors' is a 'type', but is used like a 'variable'.
有没有办法做到这一点?看起来真的很简单!
Is there a way to do this? It seems really simple!
推荐答案
您可以使用此帮助器方法获取每种颜色的名称/值对的字典.
You can use this helper method to get a Dictionary of each Color's name/value pair.
public static Dictionary<string,object> GetStaticPropertyBag(Type t)
{
const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
var map = new Dictionary<string, object>();
foreach (var prop in t.GetProperties(flags))
{
map[prop.Name] = prop.GetValue(null, null);
}
return map;
}
使用于:
var colors = GetStaticPropertyBag(typeof(Colors));
foreach(KeyValuePair<string, object> colorPair in colors)
{
Console.WriteLine(colorPair.Key);
Color color = (Color) colorPair.Value;
}
帮助方法的信用额转到如何我使用反射得到了C#静态类属性的名称?
Credit for the helper method goes to How can I get the name of a C# static class property using reflection?
这篇关于遍历所有颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!