C#, default parameter value for an IntPtr

2019-01-15 18:06发布

I'd like to use a default parameter value of IntPtr.Zero in a function that takes an IntPtr as an argument. This is not possible as IntPtr.Zero is not a compile time constant.

Is there any way I can do what I want?

2条回答
Juvenile、少年°
2楼-- · 2019-01-15 18:27

Since IntPtr is a struct, you could use Nullable-of-T?

static void SomeMethod(IntPtr? ptr = null) {
    var actualPtr = ptr ?? IntPtr.Zero;
    //...
 }
查看更多
何必那么认真
3楼-- · 2019-01-15 18:48

Somewhat unintuitive, to put it mildly, you get it by using the new operator:

    void Foo(IntPtr arg = new IntPtr()) { 
    }

That was for fun, you probably enjoy this one better:

    void Foo(IntPtr arg = default(IntPtr)) { 
    }
查看更多
登录 后发表回答