繁体   English   中英

foreach 中的 System.InvalidCastException

[英]System.InvalidCastException in foreach

我在 Visual Studio uwp 中制作了一个应用程序,并有一个堆栈面板来存储用户控件对象。 我想使用 foreach 循环访问堆栈面板中的用户控件数组。 有一个错误表明它无法将按钮转换为:“无法将类型为‘Windows.UI.Xaml.Controls.Button’的 object 转换为类型‘PopNotes.NotiObject’。”有谁知道问题出在哪里?

代码:

ArrayList notiList = new ArrayList();
    
        DispatcherTimer timer = new DispatcherTimer();
        int count = 0;
    
        public MainPage()
        {
            this.InitializeComponent();
            notificationController();
    
            foreach (NotiObject noti in itemsPanel.Children)
            {
                notiList.Add(noti);
                System.Diagnostics.Debug.WriteLine(noti);
            }
    
    
        }

有一个错误表明它无法将按钮转换为:“无法将类型为‘Windows.UI.Xaml.Controls.Button’的 object 转换为类型‘PopNotes.NotiObject。”

您看到这种情况发生是因为itemsPanel.Children集合包含NotiObject之外的其他元素。 在您的循环中,您专门针对 itemsPanel.Children 中的每个NotiObject itemsPanel.Children并非每个元素都是该集合中的NotiObject

要修复错误,您必须检查类型,因为它可以是任何元素。 有几种不同的方法,但我将列出一种方法。

foreach (NotiObject noti in itemsPanel.Children.Where(c => c is NotiObject))
{
   notiList.Add(noti);
   System.Diagnostics.Debug.WriteLine(noti);
}

在上面的示例中,我使用Enumerable.Where来仅过滤NotiObject 现在您的foreach已完成,因为Enumerable.Where中的每个 object 都是NotiObject的一种类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM