I am trying to create a generic XML to object converter. In other words, the following is my XML
<setting>
<name>testing</name>
<type>System.String</type>
<defaultObj>TTTT</defaultObj>
</setting>
the type field holds the type of the object its loading back in. This is just the object structure I serailized in. Regardless, I am having an issue converting
System.String
into an actual type variable. So for instance, in order to convert I have the following code:
foreach (XNode node in document.Element(root).Nodes())
{
T variable = new T(); //where T : new()
foreach (FieldInfo field in fields)
{
field.SetValue(variable, Convert.ChangeType(((XElement)node).Element(field.Name).Value, field.FieldType));
}
retainedList.Add(variable);
}
which obtains objects back in a generic way. The algorithm works perfectly until it comes across the Type field. I get a:
Invalid cast from 'System.String' to 'System.Type'.
run time error. From what I can tell it is having an issue directly converting a type identifier (string) directly into a type. I am not sure how to get around this issue, atleast when it comes to keeping things generic and clean. Any ideas? I am sorry if the issue is a bit vague, if you don’t quite understand I will try to clarify further. Any help is greatly appreciated!
You need to convert the string
System.Stringinto the typeSystem.String.You can do that with
Type.GetType(string typeName);For example, the
typevariable below will have theTypeobject ofSystem.String.You can then use that
Typein theConvert.ChangeTypeoverload you’re using.