Nullable类型和.HasValue仍然会抛出Null异常

Chr*_*ark 2 c# linq

我有一个类描述存储的各种电话.有时Importance属性可以为null.这是班级

public class PhoneTypeListInfo
{
    public string AccountNum { get; set; }
    public int PhoneType { get; set; }
    public string PhoneNum { get; set; }

    public int Importance { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我已经定义了一个函数,PhoneTypeListInfo如果电话号码和帐号与给定的一组值匹配,则返回a .

    protected PhoneTypeListInfo RetrievePhoneType(string info, string acctNumber)
    {
        PhoneTypeListInfo type = xPhoneTypeList.Where(p => p.PhoneNum == info && p.AccountNum == acctNumber).FirstOrDefault();

        return type;
    }
Run Code Online (Sandbox Code Playgroud)

一切都很好.我遇到的问题是下面的linq查询.

List<AlertBasedPhones> xAccountPhones = new List<AlertBasedPhones>();
xAccountPhones = (from x in xAccountStuff
                  where x.Media == "Phone"
                  let p = RetrievePhoneType(x.Info, acct.AccountNumber)
                  let xyz = x.Importance = (p.Importance as int?).HasValue ? p.Importance : 0
                  orderby p.Importance descending
                  select x).ToList();
Run Code Online (Sandbox Code Playgroud)

我上面所做的是尝试使用具有不同组成的不同类,除了从PhoneTypeListInfo获取"重要性"属性.

我的问题最终是,我需要做什么才能允许p.Importance为null,如果它为null则将其设置为0,同样为x.Importance0.

Sco*_*ain 6

这不是p.Importannce空的,而是p它本身.这是你需要首先检查null的事情.如果您使用的是C#6,则可以使用该?.运算符.您也可以smiplifiy的逻辑(p.Importance as int?).HasValue ? p.Importance : 0p.Importance ?? 0.结合两者你得到

List<AlertBasedPhones> xAccountPhones = new List<AlertBasedPhones>();
xAccountPhones = (from x in xAccountStuff
                         where x.Media == "Phone"
                         let p = RetrievePhoneType(x.Info, acct.AccountNumber)
                         let xyz = x.Importance = p?.Importance ?? 0
                         orderby p?.Importance descending
                         select x).ToList();
Run Code Online (Sandbox Code Playgroud)