将对象转换为System.Drawing.Color [英] Convert OBJECT to System.Drawing.Color

查看:80
本文介绍了将对象转换为System.Drawing.Color的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多方法可以在C#中转换颜色,包括将字符串转换为Color值,HTML转换甚至XNA框架。但是,我有一个返回System.Drawing.Color类型的对象;但由于它是一个对象,而不是颜色,因此我似乎无法在其上使用普通的颜色命令。

I know there are many ways to convert colors in C#, everything from converting strings to Color values, HTML conversion, and even XNA framework; however, I have a object that returns a type of System.Drawing.Color; but as it's an 'object', and not a 'color', i can't seem to use the normal color commands on it.

public void SetPropertyValue(string propertyName, object value)
    {
        _PropertyValues[propertyName] = value;
        Console.WriteLine("Setting Property: {0}={1}", propertyName, value);
    }

上面是用户在C#中更改属性Grid上的值时发生的情况。结果如下:

The above is what happens when a user changes a value on the property Grid in C#. The results are below:

已知名称


设置属性:Color = Color
[DimGray]

Setting Property: Color=Color [DimGray]

自定义颜色


设置属性:颜色=颜色[A = 255,R = 255,G = 255,B = 128]

Setting Property: Color=Color [A=255, R=255, G=255, B=128]

系统颜色


设置属性:Color = Color [ControlText]

Setting Property: Color=Color [ControlText]

I想要获取那里的值,然后将其实际转换为颜色,以便我可以将其包含在以前在程序中创建的defaultColor变量中。

I would like to take the values it has there, and actually convert it to a color, so that I can have it in a defaultColor variable, which was created previously in the program.

但是,因为它是一个对象,而不是实际的'System.Drawing.Color',所以我不能使用以下类似的东西:

However, as it's an object and not an actual 'System.Drawing.Color', i can't use things like:


。 ToKnownColor()

.ToKnownColor()

.ToArgb()

.ToName()

依此类推。

我知道必须有一种将对象从颜色转换为实际颜色的方法。我执行value.GetType()并返回 System.Drawing.Color ,因此系统知道它是一种颜色,但是对于我来说,我似乎无法操纵它。

I know that there has to be a way to convert from the object to an actual color. I do the value.GetType() and it returns System.Drawing.Color, so the system knows it's a color, but for the life of me i can't seem to manipulate it.

我还不是C#的专家,如果这听起来很基础,很抱歉,但是我仍然希望获得一些帮助。

I'm not an expert at C# yet, so sorry if this sounds so basic, but i'd still like some help with it.

推荐答案

将其投射为颜色

var effectiveColor = (System.Drawing.Color)value;

括号中的内容是显式强制转换,在这里您告诉编译器您了解的更多,并且变量的实际类型是另外的东西。

This thing in brackets is an explicit cast, where you tell the compiler that you know better and that an actual type of a variable is something else.

这篇关于将对象转换为System.Drawing.Color的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆