Convert string to Color in C#

后端 未结 10 1295
我寻月下人不归
我寻月下人不归 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:31

    I've used something like this before:

            public static T CreateFromString(string stringToCreateFrom) {
    
            T output = Activator.CreateInstance();
    
            if (!output.GetType().IsEnum)
                throw new IllegalTypeException();
    
            try {
                output = (T) Enum.Parse(typeof (T), stringToCreateFrom, true);
            }
            catch (Exception ex) {
                string error = "Cannot parse '" + stringToCreateFrom + "' to enum '" + typeof (T).FullName + "'";
                _logger.Error(error, ex);
                throw new IllegalArgumentException(error, ex);
            }
    
            return output;
        }
    

提交回复
热议问题