为什么我得到“'some class' 不包含 'some method' 的定义”错误,而 class 有那个方法?

why I am getting " 'some class' does not contain a definition for 'some method' " error while the class has that method?

我正在努力完成一个将 c++ 库与 c# 控制台应用程序结合使用的简单教程。 这里我有一个简单的 class 库:

cpp 文件:

#include "stdafx.h"

#include "ClassLibraryCPP.h"

using namespace ClassLibraryCPP;

void myClass::test() 
{
    Console::WriteLine("hello cpp/cli!");
}

头文件:

#pragma once

using namespace System;

namespace ClassLibraryCPP
{

    public class myClass
    {
    public:
        void test();
    };
}

现在这是我的 C# 控制台:

using ClassLibraryCPP;

namespace ConsoleApplicationCS
{
    class Program
    {
        static void Main(string[] args)
        {
            myClass testClass;
            testClass = new myClass();
            testClass.test();
        }
    }
}

我明白了:

'myClass' does not contain a definition for 'test' and no extension method 'test' accepting a first argument of type 'myClass' could be found (are you missing a using directive or an assembly reference?)

但我已经制作了 myClasstest 方法 public 那么为什么 .test() 对控制台应用程序不可见?


更新: 添加 ref 使 managed class 然后重建 C++ 项目(通过右键单击并重建而不仅仅是重建解决方案)解决了这个问题。 我还发现这个问题相关: C# code can't "see" the methods in my C++ dll 我仍然不明白这是如何工作的: https://www.youtube.com/watch?v=xTRTY-fOIe8&t=1800s

让您的 class 受管理:

public ref class myClass
{
public:
    void test();
};

更改方法声明:

void ClassLibraryCPP::myClass::test()
{
  Console::WriteLine("hello cpp/cli!");
}