c# - SDL#:为什么将 IntPtr 初始化为 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
类语义是相同的(内部IntPtr
是 always 0
)。我的总结 - 你应该关心你的应用程序的一般架构,而不是这样的微优化
推荐阅读
- c++ - 最适合速度等物理向量的 C++ 数据类型
- jena - java -cp fuseki-server.jar jena.textindexer --desc=run/cguration/FAIR.ttl 没有这样的类型:
- python-3.x - 除了 os.system() 和子进程调用之外,如何在子 shell 中执行命令(字符串)?
- sql - db.Exec() 未在 SQL Server 的 golang 中返回正确的 RowsAffected() 值
- javascript - .d.ts 用于具有返回自身的方法的模块
- c# - 如何将 UTC 字符串解析为 DateTime?
- javascript - 如何使用 brew 升级没有节点的纱线
- javascript - 使用 javascript 从特定选中的单选按钮提交表单时创建页面重定向
- r - 计算数据框中的重复行和第一个非 NA 出现
- php - 用树枝对新数组中的元素进行排序