Convert string to Color in C#

后端 未结 10 1343
我寻月下人不归
我寻月下人不归 2020-11-29 07:03

I am encountering a problem which is how do I convert input strings like \"RED\" to the actual Color type Color.Red in C#. Is there a good way to do this?

10条回答
  •  死守一世寂寞
    2020-11-29 07:44

    (It would really have been nice if you'd mentioned which Color type you were interested in to start with...)

    One simple way of doing this is to just build up a dictionary via reflection:

    public static class Colors
    {
        private static readonly Dictionary dictionary =
            typeof(Color).GetProperties(BindingFlags.Public | 
                                        BindingFlags.Static)
                         .Where(prop => prop.PropertyType == typeof(Color))
                         .ToDictionary(prop => prop.Name,
                                       prop => (Color) prop.GetValue(null, null)));
    
        public static Color FromName(string name)
        {
            // Adjust behaviour for lookup failure etc
            return dictionary[name];
        }
    }
    

    That will be relatively slow for the first lookup (while it uses reflection to find all the properties) but should be very quick after that.

    If you want it to be case-insensitive, you can pass in something like StringComparer.OrdinalIgnoreCase as an extra argument in the ToDictionary call. You can easily add TryParse etc methods should you wish.

    Of course, if you only need this in one place, don't bother with a separate class etc :)

提交回复
热议问题