问题
I want to store Color in string if they are Human Readable format and ToArgb() if they are not.
Color is Red then store it in "Red" string and If color is say some variant of green then it is store as "ff40ff80".
At runtime I want to convert this strings back to Color class Object?
回答1:
You're in luck. The Color.ToString() method will do this for you:
Return Value
Type:
System.String
A string that is the name of this Color, if the Color is created from a predefined color by using either the
FromName
method or theFromKnownColor
method; otherwise, a string that consists of the ARGB component names and their values.
回答2:
Color color = Color.Red;
string colorName = color.Name; // this gives you the ability to switch back to Color through Color.FromName()
Color sameColor = Color.FromName(colorName);
回答3:
Like Cody Gray already said it is quite simple to get the information out of the color. The problem is getting it back into a color.
So maybe this give you some kind of starting point. It is not tested, but should you give some ideas on how to solve it.
public Color FromString(string name)
{
if(String.IsNullOrWhitespace(name))
{
throw new ArgumentException("name");
}
KnownColor knownColor;
if(Enum.TryParse(name, out knownColor))
{
return Color.FromKnownColor(knownColor);
}
return ColorTranslator.FromHtml(name);
}
I just remember that there are several problems, depending on how the color is written as string. For each exists some class within the framework but they are splitted all around the namespaces (like ColorTranslator
).
Just be aware if you simply call Color.FromName(Color.FromArgb(3,4,5,6).ToString())
you'll get out a color with a name, but the argb values are all zero!
来源:https://stackoverflow.com/questions/8833127/how-to-store-colors-in-string