在 C++/CLI 中委托使用

Delegates usage in C++/CLI

我正在尝试在 C++/Cli 中使用 Delegate,我参考了 this C# 中的视频

#include <iostream>
#include"stdafx.h"

using namespace System;
using namespace System::Collections::Generic;


public ref class Employee
{
public:
    Employee() {};
    ~Employee() {};
public:
    int ID;
    String ^name;
    int Salary;
    int Experience;

public: static void Promote(List<Employee^>^ members,promoteDelegate^ promo)
{
    for each (Employee ^emp in members)
    {
        if(promo(emp))
        Console::WriteLine("{0} is Promoted", emp->name);
    }
}

};

delegate bool promoteDelegate(Employee^ emp);

ref class MyClass
{
public:
    MyClass() {};
    ~MyClass() {};

static bool func(Employee^ emp)
{
    return (emp->Salary >= 5000);
}

int main(array<System::String ^> ^args)
{
    List<Employee^> ^Employee_List = gcnew List<Employee^>;
    Employee^ emp1 = gcnew Employee;
    emp1->name = "Ajanth"; emp1->ID = 0;emp1->Salary = 50000;emp1->Experience = 3;

    Employee^ emp2 = gcnew Employee;
    emp2->name = "Aman"; emp2->ID = 1;emp2->Salary = 45000;emp2->Experience = 9;

    Employee^ emp3 = gcnew Employee;
    emp3->name = "Ashish"; emp3->ID = 2;emp3->Salary = 60000;emp3->Experience = 4;

    Employee_List->Add(emp1);
    Employee_List->Add(emp2);
    Employee_List->Add(emp3);

    promoteDelegate ^promoDel = gcnew promoteDelegate(func);

    Employee::Promote(Employee_List, promoDel); //Error here
    return 0;
}
};

我收到如下编译器错误

'Employee::Promote' does not take 2 arguments. function "Employee::Promote" cannot be called with the given argument list.
argument types are: (System::Collections::Generic::List ^, promoteDelegate ^

总是从错误列表的 top 开始。后来的消息变得越来越不可靠。您遇到的第一个错误是针对 Promote() 函数定义的,编译器尚不知道 promoteDelegate 的含义。然后会导致更多错误,例如您引用的错误。

要记住的重要规则是,与 C# 非常不同的是,C++ 编译器使用单遍编译。所有类型都必须在使用前声明。这可能会很尴尬,就像这里一样,因为委托类型本身使用 Employee 类型。必须通过 前向声明:

解决的先有鸡还是先有蛋的问题
ref class Employee;    // Forward declaration
public delegate bool promoteDelegate(Employee^ emp);

public ref class Employee
{
   // etc..
}

同时修复您的 #includes,stdafx.h 必须始终首先包含。