17

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?

4

2 回答 2

33

说得委婉些,有点不直观,你可以通过使用new运算符来获得它:

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

那是为了好玩,你可能更喜欢这个:

    void Foo(IntPtr arg = default(IntPtr)) { 
    }
于 2012-10-21T16:24:51.947 回答
5

既然IntPtr是一个结构,你可以使用 Nullable-of-T 吗?

static void SomeMethod(IntPtr? ptr = null) {
    var actualPtr = ptr ?? IntPtr.Zero;
    //...
 }
于 2012-10-21T16:08:59.843 回答