System.InvalidCastException 在 foreach 中

System.InvalidCastException in foreach

我正在 Visual Studio uwp 中制作一个应用程序,并有一个堆栈面板来存储用户控件对象。我想使用 foreach 循环访问堆栈面板中的用户控件数组。有一个错误表明它无法将按钮转换为:“无法将类型 'Windows.UI.Xaml.Controls.Button' 的对象转换为类型 '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);
            }
    
    
        }

There is an error that says that it could not convert a button to: "Unable to cast object of type 'Windows.UI.Xaml.Controls.Button' to type 'PopNotes.NotiObject."

您看到这种情况发生是因为 itemsPanel.Children 集合包含 NotiObject 之外的其他元素。在您的循环中,您具体说的是 itemsPanel.Children 中的每个 NotiObject 并非每个元素都是该集合中的 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 中的每个对象都是 NotiObject.

的一种类型