How to convert the predefined colors in a struct to a list of colors?
Asked Answered
H

1

6

There are a set of predefined colors in the SkiaSharp.SKColors struct. They are publicly exposed as static fields of type SKColor.

I want to extract those fields and create a list of SKColor. My attempt is as follows but I don't know what to do at the point indicated in the code.

using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace Example
{
    class Program
    {
       static void Main()
        {
            Type type = typeof(SKColors);
            FieldInfo[] fis = type.GetFields(BindingFlags.Static | BindingFlags.Public);
            List<SKColor> colors = new List<SKColor>();

            foreach(FieldInfo fi in fis)
            {
                //colors.Add(fi.WhatIsThis); // The point in question
            }
        }
    }
}

Here is the excerpt of SKColors:

//
// Just contains various utility colors
//
// Author:
//   Miguel de Icaza
//
// Copyright 2016 Xamarin Inc
//
using System;
namespace SkiaSharp
{
    public struct SKColors
    {
        public static SKColor Empty => new SKColor (0x00000000);
        public static SKColor AliceBlue = new SKColor (0xFFF0F8FF);
        public static SKColor AntiqueWhite = new SKColor (0xFFFAEBD7);
        public static SKColor Aqua = new SKColor (0xFF00FFFF);
        public static SKColor Aquamarine = new SKColor (0xFF7FFFD4);
        public static SKColor Azure = new SKColor (0xFFF0FFFF);
        public static SKColor Beige = new SKColor (0xFFF5F5DC);
        public static SKColor Bisque = new SKColor (0xFFFFE4C4);
        public static SKColor Black = new SKColor (0xFF000000);
        public static SKColor BlanchedAlmond = new SKColor (0xFFFFEBCD);
        public static SKColor Blue = new SKColor (0xFF0000FF);
        public static SKColor BlueViolet = new SKColor (0xFF8A2BE2);
        public static SKColor Brown = new SKColor (0xFFA52A2A);
        public static SKColor BurlyWood = new SKColor (0xFFDEB887);

        // trimmed for the sake of brevity
    }
}
Huesman answered 23/10, 2017 at 13:3 Comment(1)
(SKColor)fi.GetValue(null)Exergue
S
8

Using FieldInfo, you're only holding a reference to the field, not to its actual value.

Try this instead:

var colors = typeof(SKColors)
                .GetFields(BindingFlags.Static | BindingFlags.Public)
                .Select(fld => (SKColor)fld.GetValue(null))
                .ToList();

See MSDN

Sadiron answered 23/10, 2017 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.