首页 > 解决方案 > SDL#:为什么将 IntPtr 初始化为 null?

问题描述

我为 SDL# 找到的几个教程建议在使用前初始化变量,如下所示:

IntPtr surface = IntPtr.Zero;
surface = SDL.SDL_GetWindowSurface(window);

该代码与以下代码之间有什么实际区别吗?

IntPtr surface = SDL.SDL_GetWindowSurface(window);

根据这篇文章,在 SDL C/C++ 中,这种代码风格用于向后兼容。SDL# 也一样吗?

标签: c#sdl-2

解决方案


理论上存在差异。这是示例:

void some_method()
{
    IntPtr surface2 = IntPtr.Zero;
    surface2 = MainWindow.foo();    //  Foo's signature: IntPtr foo();
    //...
}

IL code:
{
    .maxstack 1
    .locals init (
        [0] native int
    )

    // IntPtr surface2 = IntPtr.Zero;
    IL_0000: ldsfld native int [mscorlib]System.IntPtr::Zero
    IL_0005: stloc.0
    // surface2 = MainWindow.foo();
    IL_0006: call native int WPFTest.MainWindow::foo()
    IL_000b: stloc.0
    //  ......
} 


void some_method()
{
    IntPtr surface2 = MainWindow.foo();    //  Foo's signature: IntPtr foo();
    //...
} 

IL code:
{
    .locals init (
        [0] native int
    )

    // IntPtr surface = MainWindow.foo();
    IL_0000: call native int WPFTest.MainWindow::foo()
    IL_0005: stloc.0
}

第二个代码包含较少的指令。但我认为您不应该真正关心这一点(JIT 做得很好)。在您的具体情况下,IntPtr类语义是相同的(内部IntPtr是 always 0)。我的总结 - 你应该关心你的应用程序的一般架构,而不是这样的微优化


推荐阅读