Convert string (System.String) to type

I am trying to create a general XML to object converter. In other words, this is my XML

<setting> <name>testing</name> <type>System.String</type> <defaultObj>TTTT</defaultObj> </setting> 

the type field contains the type of the object into which it is loaded. This is only the structure of the object in which I was programmed. Regardless, I'm having a conversion problem

 System.String 

into a variable of the actual type. So, for example, 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 returns objects in general. The algorithm works fine until it gets into the "Type" field. I get:

 Invalid cast from 'System.String' to 'System.Type'. 

runtime error. From what I can tell, a problem arises that directly converts the type identifier (string) directly into type. I'm not sure how to get around this problem, at least when it comes to keeping things generic and clean. Any ideas? I'm sorry if the problem is a little vague, if you do not quite understand, I will try to clarify further. Any help is much appreciated!

+4
source share
3 answers

You need to convert the string System.String to type System.String .

You can do this with Type.GetType(string typeName);

For example, the type variable below will have a type System.String object.

 var type = Type.GetType("System.String"); 

You can then use this type in the Convert.ChangeType overload that you are using.

 Convert.ChangeType(fieldValue, type); 
+7
source

See Type.GetType , which has many overloads for map types specified as strings into Type instances.

+4
source

What I need to say here, in my opinion, is that you should be a little more familiar with C # programming before you start working with serializers and deserializers. As suggested above, this particular hurdle can be solved using the Type.GetType method, however I would point you in the direction of the System.Xml.Serialization namespace, where such things have already been solved and prepared for ease of use.

-6
source

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


All Articles