你所拥有的将起作用。
foreach (Item ThisItem in TheseItems)
{
//Display properties of Item instance “ThisItem” (Excluded for ease of reading)
if (ThisItem is Computer)
{
Computer computerItem = (Computer)ThisItem;
//Display distinct properties of Computer instance “ThisItem”
}
}
或者使用as
关键字进行轻微优化:
foreach (Item ThisItem in TheseItems)
{
//Display properties of Item instance “ThisItem” (Excluded for ease of reading)
var computerItem = ThisItem as Computer;
if (computerItem != null)
{
//Display distinct properties of Computer instance “ThisItem”
}
}
另外,我的一个朋友写了一个很好的实用程序类来帮助解决这个问题。我想我会发布它,因为事实证明它非常有用。
foreach (Item ThisItem in TheseItems)
{
//Display properties of Item instance “ThisItem” (Excluded for ease of reading)
ThisItem.Match()
.Case<Computer>(comp => /* Do stuff with your computer */)
.Case<Television>(tv => /* Do stuff with your television */)
.Default(item => /* Do stuff with your item */);
}
实用程序类看起来像这样。下面给出了要点,它非常可扩展。
public class Matcher<TMatch>
{
private readonly TMatch _matchObj;
private bool _isMatched;
public Matcher(TMatch matchObj)
{
this._matchObj = matchObj;
}
public Matcher<TMatch> Case<TCase>(Action<TCase> action) where TCase : TMatch
{
if(this._matchObj is TCase)
{
this.DoCase(() => action((TCase)this._matchObj));
}
return this;
}
public void Default(Action<TMatch> action)
{
this.DoCase(() => action(this._matchObj));
}
private void DoCase(Action action)
{
if (!this._isMatched)
{
action();
this._isMatched = true;
}
}
}
public static class MatcherExtensions
{
public static Matcher<TMatch> Match<TMatch>(this TMatch matchObj)
{
return new Matcher<TMatch>(matchObj);
}
}