我通过用户界面即时创建节点列表。在我的列表中,我可以通过反射来实例化这些对象,从而根据下面的类结构向List中添加任意数量的对象(AAA,BBB等)。访问派生类中的字段
public abstract class Node : IDisposable
{
protected int x;
}
public class AAA : Node
{
public int iA;
}
public class BBB : Node
{
public int iB;
}
创建列表后,我想访问派生对象中的扩展字段。我知道我不得不沮丧地访问扩展字段,但为了做到这一点,我必须执行一个明确的演员。
foreach (Node nn in MyList) //assume the first node in the list is AAA
{
int m = ((namespace.AAA) nn).iA; //this works
int n = (AAA) nn).iA; //this works
}
我想知道如果我可以使用字符串来创建实际的downcast。也许它不能完成。也许我错过了一些东西。我想做什么不工作将是类似于以下内容。
foreach (Node nn in MyList) //assume the first node in the list is AAA
{
Type t2 = nn.GetType(); //{Name = AAA; FullName = namespace.AAA} (*debugger*)
string str = t2.FullName; //namespace.AAA
int m = ((str) nn).iA; //this DOESN'T work
}
当我在调试器中查看nn的值时,FullName表示我想用于downcast的类。
我可以通过使用switch语句来解决这个问题,该语句基于代表cast类语句中的类和硬代码的字符串,但由于我有超过100个不同的节点,我将在未来添加更多的节点,每次添加节点时都要修改switch语句。如果可能的话,我宁愿不这样做。
在此先感谢您的任何回复。
感谢Douglas指出我可以使用FieldInfo来获取iA的值。我只想在这个话题上多做一点。如果我想采用AAA类并通过组合扩展它,我也可以通过FieldInfo访问这些类中的字段。
public class AAA : Node
{
public int iA;
public X[] XArray; //where X is some other random class with pubic fields
public Y[] YArray; //where Y is some other abstract class
}
http://stackoverflow.com/questions/493490/converting-a-string-to-a-class-name – box86rowh 2013-03-22 17:17:09
这看起来像泛型的完美使用,但要说更多将需要看到更多的你的应用程序使用 – 2013-03-22 17:22:23
您是否仍然需要switch语句来知道您是否正在寻找类型为BBB的AAA或iB型属性iA? – 2013-03-22 17:27:32