gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:15:50 26 4
gpt4 key购买 nike

我有一个带有重载方法的 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++;
}
}
}

和我的 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;
}

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

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

最佳答案

作为解决方法,您可以构建一个在 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);
}
}
}

关于c# - 如何调用重载的 c# 函数,唯一的区别是在 c++/cli 中是否通过 ref 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11307162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com