【发布时间】:2011-03-16 19:14:02
【问题描述】:
我有一个基类“Element”并从中派生出另外两个类,“Solid”和“Fluid”。
class Element
{...}
class Solid : Element
{
public const int ElemType = 2;
...
}
class Fluid : Element
{
public const int ElemType = 3;
...
}
我已经创建了一个“元素”类的实例,“E1”。下面的方法应该获取一个整数“ElType”和“E1”作为其参数,并将“E1”作为“固体”或“流体”元素(或稍后将介绍的任何其他“元素”)分配给“E1”。我的意思是,如果“IElType == 2”,则应将“E1”分配给“Solid”类型,如果“IElType == 3”,则应将“Fluid”类型分配给...。我想让我的同事能够推导出尽可能多的类,来自“Element”类,并确保只有通过为“ElemType”设置适当的值,程序才能识别它们的“Element”。
private static void ElemInitializer(int ElType, out Element E1)
{
E1 = new Element();
Type T1 = typeof(Element);
Type[] T2 = Assembly.GetAssembly(T1).GetTypes();
List<Type> T3=new List<Type>();
foreach (Type t1 in T2)
{
if (t1.IsSubclassOf(T1))
{
MemberInfo[] M1 = t1.GetMembers();
foreach (MemberInfo m1 in M1)
{
if (m1.Name == "ElemType")
{
FieldInfo F1 = t1.GetField("ElemType");
int int1 = (int)F1.GetValue(t1);
if (int1 == ElType)
{
// Here I want to assign to E1 as t1 type. Such as:
// E1 = new t1(); Of course this is wrong!
}
}
}
}
}
}
这就是问题所在,我希望“E1”的类型为“t1”,但不可能通过这样的简单代码来做到这一点:
E1 = new t1(); //Of course this is wrong!
有没有办法将“E1”指定为“t1”类型?抱歉,非技术性英语。
【问题讨论】:
-
为什么在没有返回值的情况下使用out参数?