开发者

C# - Use OfType and ignore inherited classes

I have a MenuStrip with lots of items and am trying to have on event they all subscribe to so I am trying to do menuStrip1.Items.OfType<ToolStripMenuItem>(); and for each one I do this:

menuitem.Click += new EventHand开发者_开发知识库ler(MenuItem_Click);

The problem is there is a ToolStripSeperatorItem which inherits off ToolStripMenuItem and that appears is my list of items and errors because it does not have a Click event.

How can I not include these in my OfType method?


menuStrip1.Items.OfType<ToolStripMenuItem>().Where(it => it.GetType() == typeof(ToolStripMenuItem));

It seems kind of redundant, but by doing both, you maintain the return type.


menuStrip1.Items.OfType<ToolStripMenuItem>()
                .Where(i => i.GetType() == typeof(ToolStripMenuItem))


Maybe like this:

menuStrip1.Items
    .OfType<ToolStripMenuItem>()
    .Except(menuStrip1.Items.OfType<ToolStripSeparatorItem>())


menuStrip1.Items
 .Cast<ToolStripMenuItem>()
 .Where(i => i.GetType() == typeof(ToolStripSeparatorItem));

Because you don't need an implicit cast and comparision (OfType) which is basically slower then explicit cast with Cast

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜