What I am trying to do is load in objects from an XML save file. The problem is those objects are configurable by the user at runtime, meaning i had to use reflection to get the names and attributes of those objects stored in an XML file.
I am in the middle of a recursive loop through the XML and up to the part where I need to create an object then thought ..... ah - no idea how to do that :(
I have an array stuffed with empty objects (m_MenuDataTypes), one of each possible type. My recursive loading function looks like this
private void LoadMenuData(XmlNode menuDataNode)
{
foreach (object menuDataObject in m_MenuDataTypes)
{
Type menuDataObjectType = menuDataObject.GetType();
if (menuDataObjectType.Name == menuDataNode.Name)
{
//create object
}
}
}
I need to put some code where my comment is but I can't have a big switch statement or anything. The objects in my array can change depending on how the user has configured the app.
You want to use Activator.CreateInstance(Type)
object instance = Activator.CreateInstance(menuDataObjectType);
for this to work efficiently, you may need to restrict the dynamically created instances to implement an interface
ICommonInterface i = (ICommonInterface)Activator.CreateInstance(menuDataObjectType)
That way, the dynamically created object becomes usable - you can call interface methods on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With