如何调用重载的c#函数,唯一的区别是参数在c ++/cli中由ref传递的参数

czz*_*czz 10 c# overloading c++-cli tracking-reference

我有一个带有重载方法的C#类库,一个方法有一个ref参数,另一个方法有一个value参数.我可以在C#中调用这些方法,但我无法在C++/CLI中使用它.似乎编译器无法区分这两种方法.

这是我的C#代码

namespace test {
    public class test {
        public static void foo(int i)
        {
            i++;
        }
        public static void foo(ref int i)
        {
            i++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的C++/CLI代码

int main(array<System::String ^> ^args)
{
    int i=0;
    test::test::foo(i);     //error C2668: ambiguous call to overloaded function
    test::test::foo(%i);    //error C3071: operator '%' can only be applied to an instance of a ref class or a value-type
    int %r=i;
    test::test::foo(r);     //error C2668: ambiguous call to overloaded function
    Console::WriteLine(i);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我知道在C++中我不能声明重载函数,其中函数签名的唯一区别是一个接受一个对象而另一个接受一个对象,但在C#中我可以.

这是C#支持的功能,但不支持C++/CLI吗?有没有解决方法?

Seb*_*zus 1

作为解决方法,您可以构建一个在 C++/CLI 中使用的 C# 帮助程序类

namespace test
{
    public class testHelper
    {
        public static void fooByVal(int i)
        {
            test.foo(i);
        }

        public static void fooByRef(ref int i)
        {
            test.foo(ref i);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)