c#获取混合类型列表中元素的属性

Cod*_*ife -2 c# casting list

我有一个列表:圆形,三角形,矩形

我想编辑id为X的元素,但列出[X] .radius; 不可用,因为它是一个儿童班.

Mik*_*sen 7

您必须在运行时检测元素的动态类型.

IShape value = list[x];
if(value is Circle)
{
   ((Circle)value).radius = 5;
}
Run Code Online (Sandbox Code Playgroud)

你也可以这样做:

Circle value = list[x] as Circle;
if(value != null)
{
   value.radius = 5;
}
Run Code Online (Sandbox Code Playgroud)

这具有更快的优点,因为演员表只进行一次.