类型初始值设定项异常 - C#
namespace X{ public static class URLs
{
public static TabController tabIdLookUp = new TabController();
public static string DASHBOARD_AUDIT_PAGE = tabIdLookUp.GetTabByName("View My Safety", 2).TabID.ToString();
public static string URL_GENERATE_WITH_MID(String TabName, int PortalId){ {
return tabIdLookUp.GetTabByName(TabName, PortalId).TabID.ToString();
}
}}
... 在我的用户控件中,我这样做:
Response.Redirect("/" + X.URLs.URL_GENERATE_WITH_MID("test", 1)); // this causes the error
错误是:“X.URLs”的类型初始值设定项引发异常。 ---> System.NullReferenceException:未将对象引用设置为对象的实例。 at X.URLs..cctor()
无法调试,因为它在我的本地机器上工作,但在服务器上抛出该错误。
有任何想法吗?
PS,问题最终变成了一个微不足道的 NUllReferenceException - GetTabByName() 返回 NULL
namespace X{ public static class URLs
{
public static TabController tabIdLookUp = new TabController();
public static string DASHBOARD_AUDIT_PAGE = tabIdLookUp.GetTabByName("View My Safety", 2).TabID.ToString();
public static string URL_GENERATE_WITH_MID(String TabName, int PortalId){ {
return tabIdLookUp.GetTabByName(TabName, PortalId).TabID.ToString();
}
}}
...
in my user control i do this:
Response.Redirect("/" + X.URLs.URL_GENERATE_WITH_MID("test", 1)); // this causes the error
the error is: The type initializer for 'X.URLs' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object. at X.URLs..cctor()
can't debug because it works on my local box, but throws that error on the server.
any ideas?
P.S. the problem ended up being a trivial NUllReferenceException - GetTabByName() was returing NULL
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与其让“DASHBOARD AUDIT PAGE”的初始化程序直接引用 tabIdLookUp,为什么不在静态构造函数中初始化这两个变量并查看是否可以修复错误?
您可能遇到的另一个问题是,如果 GetTabByName 返回 NULL 引用,则您无法防止这种情况,而只是引用 .TabID 属性。 您应该确保在引用该属性之前获得有效的引用。
Rather than having your initializer for "DASHBOARD AUDIT PAGE" refer to tabIdLookUp directly, why not instead initialize both of those variables in a static constructor and see if that fixes the error?
Another problem you could be having is if GetTabByName is returning a NULL reference, you're not protecting against that and just referencing the .TabID property. You should probably ensure that you're getting back a valid reference before referring to the property.