语言不支持"method"



VS2010中的我的解决方案有一个CLI项目,该项目在c#项目中被引用。我在CLI中有一个名为do_something的抽象类。在C#中,我从中继承了DoSomething类。我想通过将C#实现作为抽象类参数传递来从C++运行C#实现,但抛出了"不受语言支持"异常。

CLI/c++

//abstract class
public ref class do_something{
public:
virtual void do_it()=0;
};
//using an implementation of the abstract class
public ref class cpp_caller{
public:
void run(do_something% doer){
cout<<"run c# from c++"<<endl;
doer.do_it();
}
};

c#

//implementation of abstract class
class DoSomething : do_something
{
public override void do_it()
{
Console.WriteLine("call from c#");
}
}
//inside main
DoSomething csharp_implementation = new DoSomething();
cpp_caller caller = new cpp_caller();
caller.run(csharp_implementation);

c++项目进行编译,但在编译c#代码的最后一行时,编译器抛出异常:语言不支持"run">

注意:以前的堆栈溢出解决方案没有帮助!调用run.do_it()在c#中运行良好。最后,CLI编译器不喜欢使用"^"或"&"通过引用将参数传递给run方法。

"语言不支持">

我假设您从C#而不是从C++/CLI获得此错误。

public ref class do_something
void run(do_something% doer)

C#不支持此组合:对引用类型的值的跟踪引用。

由于它是一个引用类型,C#中的do_something本身等效于C++/CLI中的do_something^。在C#中用ref do_something参数声明一个方法会使其在C++/CLI中成为do_something^%。对于引用类型,这就是C#所支持的全部内容。

C++/CLI确实支持使用ref类作为值:do_something本身为您提供堆栈语义,您可以使用do_something%传递它作为跟踪引用,但这两种方法在C#中都不使用。

传递ref类的正确方法是使用^,并使用gcnew初始化变量。其他.Net语言就是这样做的,所以如果你想从它们调用,你需要遵循它们的规则。正如您在评论中所指出的,切换到^解决了您的问题。


其他注释:

这是C++声明抽象类的方法,我甚至不知道C++/CLI仍然支持它。如果您想以托管方式声明它(我建议这样做),请在类和方法上使用关键字abstract

public ref class do_something abstract
{
public:
virtual void do_it() abstract;
};

相关内容

最新更新