作者:稀释的梦_251 | 来源:互联网 | 2023-01-28 22:18
IamencounteringaproblemwhichishowdoIconvertinputstringslikeREDtotheactualColort
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?
我遇到的问题是如何将输入字符串如“RED”转换为C#中的实际Color类型Color.Red。有没有一个很好的方法来做到这一点?
I could think of using a switch statement and cases statement for each color type but I don't think that is clever enough.
我可以考虑为每种颜色类型使用switch语句和case语句,但我认为这不够聪明。
9 个解决方案
82
Color red = Color.FromName("Red");
The MSDN doesn't say one way or another, so there's a good chance that it is case-sensitive. (UPDATE: Apparently, it is not.)
MSDN没有说出这种或那种方式,所以它很可能是区分大小写的。 (更新:显然,它不是。)
As far as I can tell, ColorTranslator.FromHtml
is also.
据我所知,ColorTranslator.FromHtml也是。
If Color.FromName
cannot find a match, it returns new Color(0,0,0);
如果Color.FromName找不到匹配项,则返回新的Color(0,0,0);
If ColorTranslator.FromHtml
cannot find a match, it throws an exception.
如果ColorTranslator.FromHtml找不到匹配项,则会抛出异常。
UPDATE:
更新:
Since you're using Microsoft.Xna.Framework.Graphics.Color, this gets a bit tricky:
由于您使用的是Microsoft.Xna.Framework.Graphics.Color,这有点棘手:
using XColor = Microsoft.Xna.Framework.Graphics.Color;
using CColor = System.Drawing.Color;
CColor clrColor = CColor.FromName("Red");
XColor xColor = new XColor(clrColor.R, clrColor.G, clrColor.B, clrColor.A);