使用LINQ在对象数组中搜索空对象

时间:2017-07-22 09:55:35

标签: c# vb.net winforms linq

我确信这很简单,但我无法弄明白,也没有找到答案, 我正在检查NumericUpDown数组中的对象是否为null (PrimaryWeightsValueChanged()由valueChange事件调用,在表单加载之前它们应该为null) 但问题是,即使在控件初始化并具有值
之后,条件也始终返回true 我做错了什么?

private NumericUpDown[] PrimaryWeightNumsAr = {
num_Primary_Billing,
num_Primary_Rutine,
num_Primary_Seker,
num_Primary_Sla
};
private void PrimaryWeightsValueChanged()
{
    // even when NumericUpDown`s are not null it enters here
    if (PrimaryWeightNumsAr.AsEnumerable().Any(x => x == null))
        return;

    // doing stuff when not null...
}

visual basic version:

Private PrimaryWeightNumsAr() As NumericUpDown = {num_Primary_Billing, num_Primary_Rutine, num_Primary_Seker, num_Primary_Sla}
Private Sub PrimaryWeightsValueChanged()
    ' even when NumericUpDown`s are not null it enters here '
    If PrimaryWeightNumsAr.AsEnumerable().Any(Function(x) x Is Nothing) Then Exit Sub

    If PrimaryWeightNumsAr.AsEnumerable().Sum(Function(x) x.Value) <> 100 Then
        For Each itm As NumericUpDown In PrimaryWeightNumsAr
            itm.BackColor = GuiProfile.sys_red
        Next
    Else
        For Each itm As NumericUpDown In PrimaryWeightNumsAr
            itm.BackColor = Color.SpringGreen
        Next
    End If
End Sub

1 个答案:

答案 0 :(得分:2)

(对于未来的观众)

根据@Ivan Stoev的评论,问题解决了。
&#34;因为字段初始化程序在类构造函数之前运行&#34; 换句话说,我的数组是在对象初始化之前声明的
在初始化数组后(在调用InitializeComponent()之后的构造函数内)将NumericUpdowns添加到数组中就可以了。 这是概括的固定代码:

Public Class PerformanceForm

    Sub New()
        ' This call is required by the designer. '
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call. '
        PrimaryWeightNumsAr = {num_Primary_Billing, num_Primary_Rutine, num_Primary_Seker, num_Primary_Sla}
    End Sub
    Private PrimaryWeightNumsAr() As NumericUpDown

    Private Sub PrimaryWeightsValueChanged()

        If PrimaryWeightNumsAr Is Nothing Then Exit Sub
        ' do other stuff... '

    End Sub

End Class

C#版本:

public class PerformanceForm
{

    public PerformanceForm()
    {
        // This call is required by the designer. 
        InitializeComponent();
        // Add any initialization after the InitializeComponent() call. 
        PrimaryWeightNumsAr = {
            num_Primary_Billing,
            num_Primary_Rutine,
            num_Primary_Seker,
            num_Primary_Sla
        };
    }

    private NumericUpDown[] PrimaryWeightNumsAr;
    private void PrimaryWeightsValueChanged()
    {

        if (PrimaryWeightNumsAr == null)
            return;
        // do other stuff... 

    }

}