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);
}
The above is what happens when a user changes a value on the property Grid in C#. The results are below:
Known Names
Setting Property: Color=Color [DimGray]
Custom Color
Setting Property: Color=Color [A=255, R=255, G=255, B=128]
System Color
Setting Property: Color=Color [ControlText]
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.
However, as it's an object and not an actual 'System.Drawing.Color', i can't use things like:
.ToKnownColor()
.ToArgb()
.ToName()
and so on.
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.
I'm not an expert at C# yet, so sorry if this sounds so basic, but i'd still like some help with it.
Cast it to Color
:
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.
The object really is a Color
, it's just being referenced by an Object reference. So all you need to do is cast it to a Color.
Color myColor = (Color)value;
// now you can do all color operations on myColor
如果仅此,您应该就可以将object
投射为Color
:
Color color = (Color)value;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.