【发布时间】:2014-05-12 14:20:34
【问题描述】:
我试图从一个类中获取对象(在我的例子中是 TabPage),但类名是作为字符串给出的。我在下面为我想要得到的东西做了一个基本的例子。我尝试过使用反射并且可以获取 PropertyInfo,但是如何获取实际对象。
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;
}
}
我已经尝试了以下代码:
Car car = new Car();
TabPage tp = (TabPage)propertyInfo[0].GetValue(car, null);
它确实有效,但想法是该类是未知的并且由字符串给出。
【问题讨论】:
标签: c# class object reflection properties