如何将可选指针参数从C++代码转换为C#

mar*_*l82 5 c# c++ arguments reference

我在c ++中有这样的功能:

// C++
bool Foo(int* retVal = NULL)
{
    // ...
    if (retVal != NULL)
        *retVal = 5;
    // ...
    return true;
}
Run Code Online (Sandbox Code Playgroud)

我可以通过两种方式使用函数:

int ret;
Foo(&ret);

Foo();
Run Code Online (Sandbox Code Playgroud)

当我用C#编写代码时,我使用了ref关键字:

// C#
bool Foo(ref int retVal = null)
{
    // ...
    if (retVal != null)
    {
        retVal = 5;
    }
    // ...
    return true;
}
Run Code Online (Sandbox Code Playgroud)

但编译说:

ref或out参数不能具有默认值.

我怎么解决这个问题?

Luc*_*ski 3

简单的方法是编写一个重载:

bool Foo()
{
    int notUsed;
    return Foo(ref notUsed);
}

bool Foo(ref int retVal)
{
    // ...
    retVal = 5;
    // ...
    return true;
}
Run Code Online (Sandbox Code Playgroud)

如果您确实需要知道是否ref需要该值,那么您仍然可以使用指针,但您需要一个unsafe上下文:

unsafe bool Foo()
{
    return Foo(null);
}

unsafe bool Foo(ref int retVal)
{
    return Foo(&retVal);
}

private unsafe bool Foo(int* retVal)
{
    // ...
    if (retVal != null)
    {
        *retVal = 5;
    }
    // ...
    return true;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果没有unsafe评论中的建议,C# 中的指针可能会被视为重炮

bool Foo()
{
    var notNeeded = 0;
    return Foo(ref notNeeded, false);
}

bool Foo(ref int retVal)
{
    return Foo(ref retVal, true);
}

private bool Foo(ref int retVal, bool retValNeeded)
{
    // ...
    if (retValNeeded)
    {
        retVal = 5;
    }
    // ...
    return true;
}
Run Code Online (Sandbox Code Playgroud)

  • @xanatos 是的,我是这样理解的 - 嘿,我毕竟没有写 `goto` :-) (2认同)