Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: instantiating classes from XML

Tags:

c#

xml

What I have is a collection of classes that all implement the same interface but can be pretty wildly different under the hood. I want to have a config file control which of the classes go into the collection upon starting the program, taking something that looks like :

<class1 prop1="foo" prop2="bar"/>

and turning that into :

blah = new class1();
blah.prop1="foo";
blah.prop2="bar";

In a very generic way. The thing I don't know how to do is take the string prop1 in the config file and turn that into the actual property accessor in the code. Are there any meta-programming facilities in C# to allow that?

like image 384
C Hogg Avatar asked Aug 27 '08 20:08

C Hogg


1 Answers

Reflection allows you to do that. You also may want to look at XML Serialization.

Type type = blah.GetType();
PropertyInfo prop = type.GetProperty("prop1");
prop.SetValue(blah, "foo", null);
like image 145
Lars Truijens Avatar answered Oct 16 '22 08:10

Lars Truijens