开发者

Casting to a derived class doesnt work on view page(aspx)

Hi Im stuck on a simple problem

Say I have a class

public Abstract Anima开发者_如何学Pythonl

And I have 2 derived classes

public Cat : Animal
{ 
    public int NumberOfLegs {get;set;}
}

So I passed this to my viewpage

System.Web.Mvc.ViewPage((IEnumerable<Animal>)

In the aspx page I can't do this(it won't even compile). It won't recognize the NumberOflegs member

foreach (item in Model)

    (Cat)item.NumberOfLegs

Any Idea?

Thanks in advance


You need to add a couple of paranthesis to have the cast evaluate before you access the member:

((Cat)item).NumberOfLegs


If you want to process only "cats" then you could filter the collection using Linq

foreach (item in Model.OfType<Cat>())
  item.NumberOfLegs
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜