简体   繁体   English

将System.Drawing.Color转换为int?

[英]Convert System.Drawing.Color to an int?

In the database, we have colors being stored as int's. 在数据库中,我们将颜色存储为int的颜色。 (Don't ask... it's a really old app.) Example: (不要问...这是一个非常老的应用程序。)示例:

-16777216 = black -16777216 =黑色

I am able to convert -16777216 to #000000 (which I can actually use in the UI): 我能够将-16777216转换为#000000(我可以在UI中实际使用):

string htmlColor = ConvertToColor("-16777216");

Will return "#000000" from this method: 将通过此方法返回"#000000"

private string ConvertColor(string value)
{
    int valInt = Convert.ToInt32(value);
    System.Drawing.Color color = System.Drawing.Color.FromArgb(valInt);
    return System.Drawing.ColorTranslator.ToHtml(color);
}

But now, to re-save the value in the same format, I'm having trouble going backwards: 但是现在,要以相同的格式重新保存值,我在倒退时遇到了麻烦:

string intColor = RevertColor("#000000");

Here's what I have so far: 这是我到目前为止的内容:

private string RevertColor(string value)
{
    System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml(value);
    return ????;
}

If FromArgb() worked going one direction, it seems like ToArgb() should work in the other direction: 如果FromArgb()朝一个方向工作,则ToArgb()应该朝另一个方向工作:

private string RevertColor(string value)
{    
    return System.Drawing.ColorTranslator.FromHtml(value).ToArgb().ToString();
}

... but I'm also not sure I appreciate all the nuances in involved. ...但是我也不确定我是否感谢所涉及的所有细微差别。 If this doesn't do the job, please explain how it fails. 如果这样做不起作用,请说明它是如何失败的。

It also seems very weird that you want a string at all, if they're really int values in the database. 如果它们实际上是数据库中的int值,那么您根本想要一个字符串似乎也很奇怪。 That scares me you might be using really unsafe practices with how you save these values in the SQL. 令我害怕的是,您可能会在将这些值保存到SQL中时使用不安全的做法。 If nothing else, it's sub-optimal for performance to convert back and forth between strings like that. 如果没有其他问题,那么像这样在字符串之间来回转换的性能次佳。 Thanks to culture/internationalization issues, those conversion operations are a lot more expensive than you might think. 由于文化/国际化问题,这些转换操作比您想象的要昂贵得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM