加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C# – 访问时内部静态只读为空

发布时间:2020-12-15 22:16:47 所属栏目:百科 来源:网络整理
导读:我有以下代码: internal class FakeInvitationsRepository : InvitationsRepository{ internal readonly static DictionaryGuid,InvitationDbEntity Data = new DictionaryGuid,InvitationDbEntity() { { ... 这是一个屏幕截图,它的价值: 它只是一些内存中
我有以下代码:

internal class FakeInvitationsRepository : InvitationsRepository
{
    internal readonly static Dictionary<Guid,InvitationDbEntity> Data = new Dictionary<Guid,InvitationDbEntity>()
    {
        { ...

这是一个屏幕截图,它的价值:

它只是一些内存中的假数据,共有3个项目.该类存在于ASP.NET WebAPI项目中,而不是在测试DLL中,而是在WebAPI DLL中.

API调用进入并在控制器操作中遇到断点,它尝试直接使用这些伪数据,没有IoC或任何聪明的东西.

但字段数据为空.它在运行时导致空引用异常.

C#语言规范说:

If a static constructor (Section 10.11) exists in the class,execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise,the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

这里发生了什么,以至于在首次使用之前该字段未初始化?

注意:一位同事已经快速检查并且也很困惑.数据只是设置,永远不会被我的代码(它的readonly afterall)取消.

编辑

这是我的代码的callstack:

System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
{   at Company.Product.WebAPI.Controllers.RenamedController.<GetInvitations>d__14.MoveNext()
   at Company.Product.WebAPI.Controllers.RenamedController.GetInvitations(Guid id)
   at lambda_method(Closure,Object,Object[] )
   at Company.WebAPI.Product.Areas.RouteDebugger.InspectActionInvoker.InvokeActionAsync(HttpActionContext actionContext,CancellationToken cancellationToken)
   at Company.WebAPI.Product.Areas.RouteDebugger.InspectHandler.<>n__FabricatedMethod12(HttpRequestMessage,CancellationToken )
   at Company.WebAPI.Product.Areas.RouteDebugger.InspectHandler.<SendAsync>d__e.MoveNext()
   at Company.WebAPI.Product.Areas.RouteDebugger.InspectHandler.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
}
    FrameCount: 84
    frames: {System.Diagnostics.StackFrame[87]}
    m_iMethodsToSkip: 3
    m_iNumOfFrames: 84

回答

我无法回答,因为问题被搁置了.值得商榷.

感谢MStodd.答案是愚蠢而直截了当的,但有点令人惊讶;我记不起在11年的.NET编程中见过这个.

数据字段尚未初始化.

在初始化程序中放置一个断点,整个块变为红色,表明它已在下一步调用.

NullReferenceException是一个红鲱鱼,由于这个原因.Invitations为null.

当然,我期望该字段在行停止时被初始化,我只是没想到它发生得太晚了,所以假设null导致我的运行时异常.

你去吧

解决方法

从您的调用堆栈中,我可以推断出对Invitations属性的评估(在Select body中).作为调用堆栈中的最后一个,我可以推断,由于Invitations为NULL,空引用会引发!).我想Data = NULL根本不与调用堆栈相关!而是它是一个调试器问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读