1

我试图在 C++/CLI 中创建一个排序委托,但是,当我尝试编译时,我收到了这个错误:

>app.cpp(256): error C3374: can't take address of 'Program::AnonymousMethod1' unless creating delegate instance
>app.cpp(256): error C2664: 'void System::Collections::Generic::List<T>::Sort(System::Comparison<T> ^)' : cannot convert parameter 1 from 'System::Object ^(__clrcall *)(Program::teste1,Program::teste1)' to 'System::Comparison<T> ^'
>          with
>          [
>              T=Program::teste1 ^
>          ]
>          No user-defined-conversion operator available, or
>          There is no context in which this conversion is possible
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

这是错误的代码示例:

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

private ref class Program
{
private:
    enum class tokens
    {
        teste,
        lala,
        blabla,
    };

    ref struct teste1
    {
        int linha;
        tokens tk;
    };

private:
    static Object ^AnonymousMethod1(teste1 p1, teste1 p2)
    {
        return p1.tk.CompareTo(p2.tk);
    }

public:
    Program()
    {
        bool jump = false;
        List<teste1^>^ lstTest = gcnew List<teste1^>();
        Random ^rnd = gcnew Random();

        for (int i = 0; i < 20; i++)
        {
            teste1 ^tst = gcnew teste1();
            switch (rnd->Next(1,4))
            {
            case 1:
                tst->tk = tokens::teste;
                break;
            case 2:
                tst->tk = tokens::lala;
                break;
            case 3:
                tst->tk = tokens::blabla;
                break;
            }
            lstTest->Add(tst);
        }

        for each (teste1^ content in lstTest)
        {
            Console::WriteLine(content->tk.ToString());
        }

        lstTest->Sort(AnonymousMethod1);

        Console::WriteLine("==============================================================");

        for each (teste1^ content in lstTest)
        {
            Console::WriteLine(content->tk.ToString());
        }
    }
};

int main(array<String^> ^args)
{
    Program^ prg = gcnew Program();
    return 0;
}

我只是想先用令牌'lala'对列表进行排序,我怎么能做到这一点,以及,我怎么能解决这个???

4

1 回答 1

2

您的列表是类型List<test1^>(注意^帽子)。所以Comparison<T>你想要的代表是Comparison<teste1^>. 因此,您需要按如下方式更改您的 AnonymousMethod1:

static int AnonymousMethod1(teste1 ^ p1, teste1 ^ p2)
{
    return p1->tk.CompareTo(p2->tk);
}

在 C++/CLI 中,您需要显式创建您的委托:

    Comparison<teste1 ^> ^ comparisonDelegate = gcnew Comparison<teste1 ^>(&AnonymousMethod1);
    lstTest->Sort(comparisonDelegate);
于 2013-04-12T15:09:22.623 回答