2013-04-12 31 views
1

我試圖在C++/CLI一種代表,但是,當我嘗試編譯我recive此埃羅:做排序使用委託

>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'對列表進行排序,我怎樣才能做到這一點,以及如何解決這個問題?

回答

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);