将 System.Drawing.Color 转换为 RGB 和十六进制值 [英] Convert System.Drawing.Color to RGB and Hex Value
问题描述
使用 C# 我试图开发以下两个.我这样做的方式可能有一些问题,需要您的善意建议.另外,我不知道是否有任何现有的方法可以做到这一点.
Using C# I was trying to develop the following two. The way I am doing it may have some problem and need your kind advice. In addition, I dont know whether there is any existing method to do the same.
private static String HexConverter(System.Drawing.Color c)
{
String rtn = String.Empty;
try
{
rtn = "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}
catch (Exception ex)
{
//doing nothing
}
return rtn;
}
private static String RGBConverter(System.Drawing.Color c)
{
String rtn = String.Empty;
try
{
rtn = "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}
catch (Exception ex)
{
//doing nothing
}
return rtn;
}
谢谢.
推荐答案
我没看到这里的问题.代码看起来不错.
I'm failing to see the problem here. The code looks good to me.
我唯一能想到的就是 try/catch 块是多余的 -- Color 是一个结构体,R、G 和 B 是字节,所以 c 不能为 null 并且 cRToString()
、cGToString()
和 cBToString()
实际上不会失败(我看到它们失败的唯一方法是使用 NullReferenceException
,它们实际上都不能为空).
The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and c.R.ToString()
, c.G.ToString()
, and c.B.ToString()
can't actually fail (the only way I can see them failing is with a NullReferenceException
, and none of them can actually be null).
您可以使用以下方法清理整个内容:
You could clean the whole thing up using the following:
private static String HexConverter(System.Drawing.Color c)
{
return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}
private static String RGBConverter(System.Drawing.Color c)
{
return "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}
这篇关于将 System.Drawing.Color 转换为 RGB 和十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!