我有一个名为players
的可观察集合,其中包含各种Player
个对象。
所有对象都从Player
对象继承属性,但是具有一些独特属性的不同类,例如Goalkeeper
和Defender
等
如何检查可观察集合中的对象类型并相应地更改其唯一属性?
foreach (Player p in players)
{
if(p.GetType().Name == "Goalkeeper")
{
p.Saves == 100;
}
else if (p.GetType().Name == "Defender")
{
p.Tackles = 50;
}
}
答案 0 :(得分:6)
使用is
和as
:
foreach (var p in players)
{
if (p is Goalkeeper)
{
var goalie = p as Goalkeeper;
goalie.Saves == 100;
}
else if (p is Defender)
{
var defender = p as Defender;
defender.Tackles = 50;
}
}
作为注释:C#7(在Visual Studio 2017中提供)有一些新的语法来简化这些,以消除对单独的is
和as
语句的需要,以及一些增强功能switch
声明。
switch(p)
{
case Goalkeeper goalie:
goalie.Saves == 100;
break;
case Defender defender:
defender.Tackles = 50;
break;
/* ... */
default:
throw new Exception("Unknown Player Type");
break;
}