gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:43:31 25 4
gpt4 key购买 nike

<分区>

我有以下代码:

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

这是一个屏幕截图,看它的值(value):

Screen shot of real code

只是一些内存中的假数据,一共3项。该类位于 ASP.NET WebAPI 项目中,而不是在测试 DLL 中,但暂时位于 WebAPI DLL 中。

一个 API 调用进入并在 Controller 操作中命中一个断点,它试图直接使用这个假数据,还没有 IoC 或任何聪明的东西。

但是 Data 字段为空。它在运行时导致空引用异常。

Screen show showing null

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.

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

注意:一位同事很快就进行了理智检查,也感到困惑。 Data 只被设置,永远不会被我的代码清空(毕竟它是只读的)。

编辑

这是我的代码的调用堆栈:

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 编程中见过这种情况。

Data 字段尚未初始化。

在初始化器中放置一个断点,整个 block 变红,表明它在下一步被调用。

NullReferenceException 是个误会,因为 this.Invitations 为 null。

当然,我希望该行在该行停止时初始化该字段,我只是没想到它会这么晚发生,所以假设 null 导致我运行时异常。

给你。

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