C# NotifyCollectionChangedEventArgs检查它包含的内容

C# NotifyCollectionChangedEventArgs检查它包含的内容,c#,C#,这是我作为参数使用的方法的实现: System.Collections.Specialized.NotifyCollectionChangedEventHandler -> 正如你所看到的,我使用三重检查来确保程序不会在这里崩溃 有没有更好的办法解决这个问题 谢谢大家! 我会这样做的 void _students_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { string name = str

这是我作为参数使用的方法的实现:

System.Collections.Specialized.NotifyCollectionChangedEventHandler

->

正如你所看到的,我使用三重检查来确保程序不会在这里崩溃

有没有更好的办法解决这个问题


谢谢大家!

我会这样做的

void _students_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    string name = string.Empty;

     if (e.NewItems != null && e.NewItems.Count > 0)
    {
        var student = e.NewItems[0] as Student;
        if (student != null) name = student.Name;
    }

    lstLog.Items.Add(string.Format("{0} Name:", name)); 
}

我会这样做的

void _students_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    string name = string.Empty;

     if (e.NewItems != null && e.NewItems.Count > 0)
    {
        var student = e.NewItems[0] as Student;
        if (student != null) name = student.Name;
    }

    lstLog.Items.Add(string.Format("{0} Name:", name)); 
}

我不确定是否需要检查
e.NewItems.Count>0
,因为如果没有添加任何内容,它通常为空。而不是
e.NewItems[0]!=null&&e.NewItems[0]是学生
,您只需执行
e.NewItems[0]是学生
,因为
null是学生
是false。即使name/xxx变量为空,也存在记录某些内容的问题。这可能有点滥用,但你可以这样做:

var student = (e.NewItems ?? new List<Student>()).OfType<Student>().FirstOrDefault();
if (student != null)
    lstLog.Items.Add(string.Format("Name: {0}", student.Name));

我不确定是否需要检查
e.NewItems.Count>0
,因为如果没有添加任何内容,它通常为空。而不是
e.NewItems[0]!=null&&e.NewItems[0]是学生
,您只需执行
e.NewItems[0]是学生
,因为
null是学生
是false。即使name/xxx变量为空,也存在记录某些内容的问题。这可能有点滥用,但你可以这样做:

var student = (e.NewItems ?? new List<Student>()).OfType<Student>().FirstOrDefault();
if (student != null)
    lstLog.Items.Add(string.Format("Name: {0}", student.Name));

我想你忘了检查收藏中是否有物品。。。e、 NewItems.count我想你忘了检查收藏中是否有物品。。。e、 NewItems.count这是我第一次看到操作员。谢谢您的示例。这是我第一次看到
??
运算符。谢谢你的例子。