Reputation: 3
I am trying to get the object (in my case a TabPage) from a class but the class name is given as a string. I have done a basic example below for what I am trying to get. I have tried using reflection and can get the PropertyInfo but how do I get the actual object.
public Form1()
{
string TabName = "Car";
InitializeComponent();
/*
* Need the ability to get Class from string Name then get ConfigurationTab from that class
* PropertyInfo[] propertyInfo = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Name == TabName).FirstOrDefault().GetProperties();
*/
}
public class Car
{
public TabPage _Tab;
public TabPage ConfigurationTab { get { return _Tab; } }
public Car()
{
_Tab = new TabPage("Car");
_Tab.BackColor = Color.Red;
}
}
public class Truck
{
public TabPage _Tab;
public TabPage ConfigurationTab { get { return _Tab; } }
public Truck()
{
_Tab = new TabPage("Truck");
_Tab.BackColor = Color.Blue;
}
}
I have tried the follow code:
Car car = new Car();
TabPage tp = (TabPage)propertyInfo[0].GetValue(car, null);
and it does work but the idea is the class is not known and given by a string.
Upvotes: 0
Views: 92
Reputation: 12857
You could do this:
object obj = Activator.CreateInstance(Type.GetType("Car")));
However because your Car
and Truck
class do not share a common class or interface you can only use object
as the type of obj
unless you cased the type etc... but that would be pointless and not get you dynamic creation.
To solve, there are multiple ways but here is a simple one, use a common base class:
public class Base //<--- use a better name than that... lol
{
protected TabPage _Tab;
public TabPage ConfigurationTab { get { return _Tab; } }
public Base() {}
}
Now extend the base class for Car and Truck:
public class Car : Base
{
public Car()
{
_Tab = new TabPage("Car");
_Tab.BackColor = Color.Red;
}
}
public class Truck : Base
{
public Truck()
{
_Tab = new TabPage("Truck");
_Tab.BackColor = Color.Blue;
}
}
Now change your Activator:
Base base = (Base) Activator.CreateInstance(Type.GetType("<TheClassToCreate>")));
Upvotes: 1