对于强类型,初始化var值为null

本文关键字:var 值为 null 初始化 强类型 | 更新日期: 2023-09-27 18:12:25

我正在尝试做以下事情:

我不确定如何初始化resultcllist,因为我不能将其设置为null。

    var resultCLlist = null;
    if (RdoStatus.SelectedValue == "Incomplete")
    {
         resultCLList = (from ms in db.ver_ServiceReport
                            join gc in db.map_Sit 
                            on ms.SiteId equals gc.SiteID
                            where gc.CompanyId == companyId
                            select new ServiceReport
                            {
                                VerificationId = ms.VerificationId,
                                SiteId = ms.SiteId,
                            }
                         ).ToList();
    }
    else
    {
         resultCLList = (from ms in db.ver_ServiceReport
                            join gc in db.map_Sites
                            on ms.SiteId equals gc.SiteID
                            where gc.CompanyId == companyId
                            select new ServiceReport
                            {
                                VerificationId = ms.VerificationId,
                                SiteId = ms.SiteId,
                                SiteName = gc.SiteName,
                                TimeStamp = ms.TimeStamp,
                                EntryDate = ms.EntryDate,
                                Supplier = ms.Supplier
                            }
                        ).ToList();
    }

对于强类型,初始化var值为null

为什么不用List<ServiceReport>而不用var呢?

不能将var初始化为null值,因为null本身不是类型。您可以将其强制转换为object,但这并不安全。如果您不知道右侧表达式的返回类型,或者类型名称太长,var很有用。在本例中,您知道该类型,因此不使用var