转换的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;
}
感谢。
推荐答案
我没有看到这里的问题。在code对我来说很好。
I'm failing to see the problem here. The code looks good to me.
我能想到的唯一的事情是,try / catch块是多余的 - 颜色是一个结构和R,G和B是字节,所以C不能为空和 CR的ToString()
, 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屋!