C#WinForms System.InvalidCastException

时间:2016-12-12 22:32:52

标签: c# winforms

我有一个带有工具条按钮的C#WinForms应用程序和两个名为"frmMultiCategoryProject""frmTiebreaker"的MDI ChildForms。工具条按钮的Click()事件会发生不同的操作,具体取决于工具条按钮的Text属性。

以下是代码:

    private void tsbtnAddShowTiebreaker_Click(object sender, EventArgs e)
    {
        if (tsbtnAddShowTiebreaker.Text == "Add Tiebreaker" || tsbtnAddShowTiebreaker.Text == "Show Tiebreaker")
        {
            foreach (frmMultiCategoryProject frmamdic in this.MdiChildren)
            {
                frmamdic.SendToBack();
                frmamdic.Hide();
                frmamdic.Visible = false;
            }
            frmTiebreaker frmTB = new frmTiebreaker(Tiebreaker);
            frmTB.MdiParent = this;
            frmTB.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            frmTB.Dock = DockStyle.Fill;
            frmTB.Show();
            tsbtnCloseProject.Visible = true;
            frmTB.BringToFront();
            tsbtnAddShowTiebreaker.Text = "Hide Tiebreaker";
        }
        else if (tsbtnAddShowTiebreaker.Text == "Hide Tiebreaker")
        {
            string strMdiChildren = "";

            foreach (frmTiebreaker frmTB in this.MdiChildren)    // This is where the InvalidCastException occurs.
            {
                strMdiChildren += frmTB.Name.ToString() + "\r\n";
                this.Tiebreaker = frmTB.Tiebreaker;
                frmTB.Dispose();
            }

            foreach (frmMultiCategoryProject frmamdic in this.MdiChildren)
            {
                frmamdic.BringToFront();
                frmamdic.Show();
            }

            tsbtnAddShowTiebreaker.Text = "Show Tiebreaker";
        }
    }  

这就是问题所在(frmMain.cs:第2359行是评论的那个):

System.InvalidCastException was unhandled
  HResult=-2147467262
Message=Unable to cast object of type 'Trivia_Author_v20.frmMultiCategoryProject' to type 'Trivia_Author_v20.frmTiebreaker'.
  Source=Trivia Author v20
  StackTrace:
       at Trivia_Author_v20.frmMain.tsbtnAddShowTBIsClicked() in c:\Users\Reuben\Documents\Visual Studio 2013\TRIVIA AUTHOR SUITE V20 PROJECTS 2\TAS v20 frmTB 2\Trivia Author v10 New Approach\frmMain.cs:line 2359
       at Trivia_Author_v20.frmMain.tsbtnAddShowTiebreaker_Click(Object sender, EventArgs e) in c:\Users\Reuben\Documents\Visual Studio 2013\TRIVIA AUTHOR SUITE V20 PROJECTS 2\TAS v20 frmTB 2\Trivia Author v10 New Approach\frmMain.cs:line 2256
       at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
       at System.Windows.Forms.ToolStripButton.OnClick(EventArgs e)
       at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
       at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
       at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
       at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
       at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ToolStrip.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at Trivia_Author_v20.Program.Main(String[] args) in c:\Users\Reuben\Documents\Visual Studio 2013\TRIVIA AUTHOR SUITE V20 PROJECTS 2\TAS v20 frmTB 2\Trivia Author v10 New Approach\Program.cs:line 116
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at System.Activator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

为什么我的代码无法告诉他们在任何时候处理哪种类型的表单?

1 个答案:

答案 0 :(得分:5)

foreach循环不会将其项目过滤为您声明的类型;它只是试图强制转换,并在失败时抛出该异常。

要过滤,请使用.OfType<T>()