SDL#:为什么将 IntPtr 初始化为空?
SDL#: Why initialize IntPtr to null?
我找到的一些 SDL# 教程建议在使用前初始化变量,如下所示:
IntPtr surface = IntPtr.Zero;
surface = SDL.SDL_GetWindowSurface(window);
该代码与以下代码之间有什么实际区别吗?
IntPtr surface = SDL.SDL_GetWindowSurface(window);
根据 ,在 SDL C/C++ 中,此代码风格用于向后兼容的原因。 SDL#也是这样吗?
理论上存在差异。这是示例:
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
class 语义的具体情况下是相同的(内部 IntPtr
总是 0
)。我的总结 - 你应该关心你的应用程序的一般架构而不是这样的微优化
我找到的一些 SDL# 教程建议在使用前初始化变量,如下所示:
IntPtr surface = IntPtr.Zero;
surface = SDL.SDL_GetWindowSurface(window);
该代码与以下代码之间有什么实际区别吗?
IntPtr surface = SDL.SDL_GetWindowSurface(window);
根据
理论上存在差异。这是示例:
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
class 语义的具体情况下是相同的(内部 IntPtr
总是 0
)。我的总结 - 你应该关心你的应用程序的一般架构而不是这样的微优化