How can I get System.Type from the string "System.Drawing.Color"

I have an xml stored property of some control

<Prop Name="ForeColor" Type="System.Drawing.Color" Value="-16777216" /> 

I want to convert it back like others

 System.Type type = System.Type.GetType(propertyTypeString); object propertyObj = TypeDescriptor.GetConverter(type).ConvertFromString(propertyValueString); 

System.Type.GetType ("System.Drawing.Color") returns null.

The question is how to get the color type from the string correctly.

(it’s better not to make a special case only for color properties)

Update

from time to time this xml will be edited manually

+4
source share
4 answers

You need to specify the assembly as well as the type name when using Type.GetType() , unless the type is in mscorlib or the assembly currently in mscorlib .

If you know this in the System.Drawing assembly, you can use Assembly.GetType() instead - or perhaps look at the whole list of possible assemblies:

 Type type = candidateAssemblies.Select(assembly => assembly.GetType(typeName)) .Where(type => type != null) .FirstOrDefault(); if (type != null) { // Use it } else { // Couldn't find the right type } 
+4
source

Do you have the System.Drawing assembly loaded? Do you have a link to it?

+2
source

Do you store these properties in XML? If so, just create an AssemblyQualifiedName object instead of FullName when creating the node. This gives the assembly context information needed to load a type from a string using Type.GetType()

+2
source

Perhaps this does not entirely apply to your problem, but I had a similar one. I needed to serialize / deserialize the color using XmlSerializer . After searching the Internet and combining the wisdom of several authors, I came up with a wrapper class:

 /// <summary> /// Color that can be xml-serialized /// </summary> public class SerializableColor { public int A { get; set; } public int R { get; set; } public int G { get; set; } public int B { get; set; } public int KnownColor { get; set; } /// <summary> /// Intended for xml serialization purposes only /// </summary> private SerializableColor() { } public SerializableColor(Color color) { this.A = color.A; this.R = color.R; this.G = color.G; this.B = color.B; this.KnownColor = (int)color.ToKnownColor(); } public static SerializableColor FromColor(Color color) { return new SerializableColor(color); } public Color ToColor() { if (KnownColor != 0) { return Color.FromKnownColor((KnownColor)KnownColor); } else { return Color.FromArgb(A, R, G, B); } } } 

Perhaps this can be applied to your situation. You see, the color class is sometimes stored not as a combination of ARGB values, but as a value of the KnownColor enumeration ... which must be preserved during serialization.

0
source

Source: https://habr.com/ru/post/1285662/


All Articles