C#: instantiating classes from XML

前端 未结 8 794
情歌与酒
情歌与酒 2021-02-04 09:05

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

8条回答
  •  广开言路
    2021-02-04 09:27

    Plenty of metaprogramming facilities.

    Specifically, you can get a reference to the assembly that holds these classes, then easily get the Type of a class from its name. See Assembly.GetType Method (String).

    From there, you can instantiate the class using Activator or the constructor of the Type itself. See Activator.CreateInstance Method.

    Once you have an instance, you can set properties by again using the Type object. See Type.GetProperty Method and/or Type.GetField Method along PropertyInfo.SetValue Method.

提交回复
热议问题