gpt4 book ai didi

c# - 对象引用未设置错误 INSIDE != null 仅当 block ?

转载 作者:太空宇宙 更新时间:2023-11-03 22:24:14 25 4
gpt4 key购买 nike

存储库代码:

public IQueryable<Bundle> getAllCustomBundlesByCompanyID(int companyID)
{
return from companyBundle in db.CompanyBundles
join bundle in db.Bundles on companyBundle.BundleID equals bundle.BundleID
where companyBundle.CompanyID == companyID && bundle.CompanyID == companyID
orderby bundle.BundleName ascending
select bundle;
}

Controller 代码:

    ViewData["OurCategories"] = bundleRepository.getAllCustomBundlesByCompanyID(CompanyID);

查看代码:

    <ul class="SmallCats">
<%if(ViewData["OurCategories"] != null){ %>
<%List<KODmvc.Models.Bundle> ourCategories = ViewData["OurCategories"] as List<KODmvc.Models.Bundle>; %>
<%foreach(KODmvc.Models.Bundle b in ourCategories) { %>
<li><a href="<%=b.BundleID%>">
<img src="/Content/images/bundleicons/<%=b.BundleIcon %>" />
<%=b.BundleName %></a>
</li>
<%} %>
<%} else { %>
There are no custom categories.
<%} %>

</ul>

错误:

 Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 38: <%if(ViewData["OurCategories"] != null){ %>
Line 39: <%List<KODmvc.Models.Bundle> ourCategories = ViewData["OurCategories"] as List<KODmvc.Models.Bundle>; %>
Line 40: <%foreach(KODmvc.Models.Bundle b in ourCategories) { %>
Line 41: <li><a href="<%=b.BundleID%>">
Line 42: <img src="/Content/images/bundleicons/<%=b.BundleIcon %>" />


Source File: e:\Bancroft Archive\PanamaTrunk\Views\Asset\AdminDashboard.aspx Line: 40

但我正在检查以确保 ViewData 不为空,然后再让它进入,这到底是怎么回事??

最佳答案

好吧,如果 as 转换与您提供的类型不匹配,那么它会返回 null。您的 foreach 取消引用 ourCategories,此时它可能为 null。

如果您不打算显式测试 ourCategories 是否为 null,则应该使用 () 转换。然后,如果转换失败,您将收到一个有意义的错误。

关于c# - 对象引用未设置错误 INSIDE != null 仅当 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1986487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com