简体   繁体   中英

Serialize Class obtained using Reflection to XML

I have a file that looks like the following:

public abstract class TestStep
{
   public abstract bool DoWork();
   public abstract List<TestStep> PrerequisiteSteps { get; set; }
   public abstract string DisplayForm { get; }
}

class TestFunctions
{
   public class A : TestStep
   {
      public override string DisplayForm { get { return "MainForm; } }
      // remaining implementation goes here...
   }
   public class B : TestStep { // some implementation }
   public class C : TestStep { // some implementation }
   public static void NextStep() { }
}

I'd like to serialize the classes A , B , and C to an XML file. I can manually add instances of these classes to a List<TestStep> object and pass that to an XML serializer, but I'd like to programmatically accomplish this because I might add or remove classes in TestFunctions in the future. As a result, I've found that I can use reflection to get an array of the functions:

Type type = (typeof(TestEngineFunctions));
Type[] testEngineFunctions = type.GetNestedTypes(BindingFlags.Public);

However I'm not sure how to proceed from here. I have access to the name of the functions, I can get their properties as well, but ultimately I don't have an actual object to serialize.
Am I on the right track or is there another method better suited for this?

You can get a new instance of the objects like this:

ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);

Since you may not know the ObjectType before run time you could use the dynamic type and don't cast:

dynamic instance = Activator.CreateInstance(objectType);

However, if you attempt to serialize right after you instantiate you'll just get the default values of the object in your XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM