循环遍历所有颜色?

pea*_*ewg 2 c# silverlight windows-phone-7

我正在使用C#(Windows-Phone-7)中的应用程序,我正在尝试做一些让我难过的简单事情.

我想循环遍历颜色中的每个颜色,并将颜色名称写入文件(以及其他内容).

我有最简单的代码,我知道这些代码不起作用,但我写信开始:

foreach (Color myColor in Colors)
{
}
Run Code Online (Sandbox Code Playgroud)

当然,这给了我以下语法错误:

'System.Windows.Media.Colors'是'type',但用作'变量'.

有没有办法做到这一点?看起来真的很简单!

mfa*_*nto 7

您可以使用此辅助方法获取每个Color的名称/值对的Dictionary.

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;
    }
Run Code Online (Sandbox Code Playgroud)

用途是:

var colors = GetStaticPropertyBag(typeof(Colors));

foreach(KeyValuePair<string, object> colorPair in colors)
{
     Console.WriteLine(colorPair.Key);
     Color color = (Color) colorPair.Value;
}
Run Code Online (Sandbox Code Playgroud)

对辅助方法的信用是 如何使用反射获取C#静态类属性的名称?


Ree*_*sey 6

您可以使用Reflection获取Colors类型中的所有属性:

var colorProperties = Colors.GetType().GetProperties(BindingFlags.Static | BindingFlags.Public);
var colors = colorProperties.Select(prop => (Color)prop.GetValue(null, null));
foreach(Color myColor in colors)
{
    // ....
Run Code Online (Sandbox Code Playgroud)