当我在 NET Framework 4.7.2 中创建新的 WPF 应用程序时,将菜单添加到 MainWindow 时,每当您单击菜单然后单击菜单以外的位置将其关闭时,我都会收到 InvalidCastException
。
当它从 PresentationFramework.dll
中抛出时,我可以忽略此异常,一切正常我只是想知道这是 NET Framework 问题还是我做错了什么?
完整的解决方案可以在这里找到https://github.com/glrad/InvalidCastException
App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
var view = new MainWindow();
MainWindow = view;
view.Show();
}
主窗口.xaml
<Window x:Class="MyApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="GASGC3" Height="800" Width="1000">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Menu Grid.Row="0">
<MenuItem Header="File">
<MenuItem Header="Options" InputGestureText="Ctrl+O"/>
<Separator/>
<MenuItem Header="Exit" InputGestureText="Alt+F4" />
</MenuItem>
<MenuItem Header="Help">
<MenuItem Header="About" />
</MenuItem>
</Menu>
</Grid>
</Window>
异常抛出:
System.InvalidCastException: 'Unable to cast object of type 'System.Collections.Hashtable' to type 'System.String'.'
最佳答案
您看到此异常似乎是因为您更改了 Visual Studio 中的异常设置并启用了 CLR 异常。
如果您选中Break when thrown: Common Language Runtime Exceptions,那么您将看到已捕获的异常,否则永远不会冒泡给用户。这些异常是正常的。
只有在跟踪难以发现的错误时,才应启用中断 CLR 异常。通常您甚至可以设置一个断点,在关闭 CLR 异常的情况下启动应用程序(以避免一直遇到它们),然后,当遇到断点时,选中此选项并继续仅测试特定代码。如果您想查看已处理并在 try-catch 语句中默默吞下的异常,通常您会这样做。
请注意,这显示了已处理的异常,所以不要担心它们。
关于c# - 为什么在我打开然后关闭窗口上的菜单时会出现 InvalidCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57309591/