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.String
into the type System.String
.
You can do that with Type.GetType(string typeName);
For example, the type
variable below will have the Type
object of System.String
.
var type = Type.GetType("System.String");
You can then use that Type
in the Convert.ChangeType
overload you're using.
Convert.ChangeType(fieldValue, type);
Take a look at Type.GetType which has a variety of overloads to maps type specified as string to Type
instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With