[英]Retrieve non-abstract class property value from abstract class variable
I have a library where ModelElement is an abstract class and ModelBeam and ModelShell are classes inherited from ModelElement. 我有一个库,其中ModelElement是抽象类,而ModelBeam和ModelShell是从ModelElement继承的类。 ModelShell specifically have a propriety called "mesh" and it's value is a Mesh class. ModelShell专门具有一个称为“ mesh”的专有属性,其值是Mesh类。 I wonder how I can retrieve the Mesh from a ModelElement variable after checking that the variable is a ModelShell object. 我不知道如何在检查变量是ModelShell对象之后如何从ModelElement变量检索Mesh。
I wish something like the code above: 我希望类似上面的代码:
foreach (ModelElement elem in model.elems)
{
if (elem.GetType() == typeof(ModelBeam))
{
conect.Add(elem._node_inds);
}
if (elem.GetType() == typeof(ModelShell))
{
Mesh mesh = elem.mesh;
foreach (Mesh m in mesh)
{
conect.Add(m._node_inds);
}
}
}
Use the is
keyword and then a direct cast: 使用is
关键字,然后直接转换:
if (elem is ModelShell)
{
var modelShell = (ModelShell)elem;
foreach (var m in modelShell.mesh)
{
//...
}
}
If the elem
isn't ModelShell
this will return false and never enter the if block. 如果elem
不是ModelShell
则它将返回false,并且永远不会输入if块。
Alternatively, you can use the as
keyword. 或者,您可以使用as
关键字。 This one performs a cast if you casting using a correct type or else results in null
. 如果使用正确的类型进行转换,则此转换将执行强制转换,否则将导致null
。 So after casting you need to check if the variable is null
or not. 因此,在强制转换之后,您需要检查变量是否为null
。
var modelShell = elem as ModelShell;
if (modelShell != null)
{
foreach (var m in modelShell.mesh)
{
//...
}
}
You may try this .. 你可以试试这个..
if(elem instanceof ModelBeam){
}else if(elem instanceof ModelShell){
}
Try following code. 尝试以下代码。 Basically, using operator is and casting to ModelShell should work. 基本上,使用operator is并强制转换为ModelShell即可。
foreach (ModelElement elem in model.elems)
{
if (elem is ModelBeam)
{
conect.Add(elem._node_inds);
}
if (elem is ModelShell)
{
Mesh mesh = ((ModelShell)elem).mesh;
foreach (Mesh m in mesh)
{
conect.Add(m._node_inds);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.