我尝试在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'对列表进行排序,我怎么能做到这一点,以及如何解决这个问题?
答案 0 :(得分: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);