这两个陈述之间有什么区别:
IntPtr myPtr = new IntPtr(0);
IntPtr myPtr2 = IntPtr.Zero;
Run Code Online (Sandbox Code Playgroud)
我已经看到许多使用PInvoke的示例,如果myPtr参数由ref发送到被调用函数,则它更喜欢第一种语法.如果我在我的应用程序中用IntPtr.Zero替换所有新的IntPtr(0),它会造成任何损害吗?
Kei*_*ith 24
IntPtr
是一种值类型,因此与String.Empty
静态属性相比,它的好处不大IntPtr.Zero
一旦你通过IntPtr.Zero
任何地方你就会得到一份副本,所以对于变量初始化它没有任何区别:
IntPtr myPtr = new IntPtr(0);
IntPtr myPtr2 = IntPtr.Zero;
//using myPtr or myPtr2 makes no difference
//you can pass myPtr2 by ref, it's now a copy
Run Code Online (Sandbox Code Playgroud)
有一个例外,那就是比较:
if( myPtr != new IntPtr(0) ) {
//new pointer initialised to check
}
if( myPtr != IntPtr.Zero ) {
//no new pointer needed
}
Run Code Online (Sandbox Code Playgroud)
正如几张海报已经说过的那样.
它们在功能上是等价的,因此它不会引起任何问题.
IntPtr.Zero
代表结构的默认状态(它被声明,但不使用的构造),所以的默认值intptr (void*)
是null
.然而,由于(void*)null
和(void*)0
是等价的,IntPtr.Zero == new IntPtr(0)
编辑:虽然它们是等价的,但我建议IntPtr.Zero
用于比较,因为它更容易阅读.