开发者

How to use reflection to instantiate a new class based on text in an xml file

i have a base Question class and lot of classes that derives from this class like CheckboxQuestion class and RadioButtonQuestion class

the program iterates over xml code for every block that is inside a question tag it will make a new element based on the tag's name and is a child class of the Question class

        <question number="1"&开发者_如何学JAVAgt;
            <RadioButtonQuestion>
                <title>What is the right ...</title>
                <choices>
                    <choice value="1">answer 1</choice>
                    <choice value="2">answer 2</choice>
                    <choice value="3">answer 3</choice>
                    <choice value="4">answer 4</choice>
                </choices>
            </RadioButtonQuestion>
        </question>

after iterating on all the xml file i want to put all the questions in IEnumerable<Questions> the problem is that i don't know how to make a new class based on the text written in an xml document


If the XML tag directly reflects the name of your class you can use Type.GetType() to determine the corresponding type - keep in mind that it needs the full namespace though ("Test" in the example below). Then you can use Activator.CreateInstance() to create an instance of that type.

string xmlTagName = "RadioButtonQuestion";
Type type = Type.GetType("Test." + xmlTagName );
var question = Activator.CreateInstance(type);

Also keep in mind that Activator.CreateInstance() returns object. It might be better overall if you determined the right type depending on the tag name, and then instantiated an instance the old fashioned way.


Assuming the types are all in the currently executing assembly, this should instantiate the class by name without needing the switch statement:

public object InstantiateClass(string name, params object[] args)
{
    return Activator.CreateInstance(this.GetType().Assembly.FullName, name, args);
}


 switch(input)
 {
      case optionA:
          return Activator.CreateInstance(typeof(Bla));
      case optionB:
          return Activator.CreateInstance(typeof(Blb));
 }

$0.02

Any extra parameters to the constructor of Bla/Blo can be added

Activator.CreateInstance(typeof(Bla), 1, 2 ,3);

Actually, it takes a params array of objects. So if you needed to pass them dynamically,

object[] dynparams = new object[] { 1,2, "more", 4.5, new List<int>() };
...
return Activator.CreateInstance(typeof(Bla), dynparams);

Numerous other overloads exist, read about them here

Now I don't know any of your typenames, but you will be able to do

Object obj = Activator.CreateInstance(null, "Namespace1.MyClass1", dynparams);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜