私はいつも「いいえ、できません」と言う人が好きではありません。;-)
したがって、私の答えは:はい、できます!
もともと、オーバーロードされた非ジェネリック メソッドをジェネリック メソッドから呼び出したいと考えていました。コンパイラはそれが好きではありませんでした。可能な解決策はSO 5666004およびSO 3905398にありますが、非常に複雑であることがわかりました。
この記事や他の投稿や記事を読んだ後、頭の片隅に漠然とした考えが浮かびました。試行錯誤と新しい機能の学習により、実用的なソリューションにたどり着きました。
他の人は正しいです。各デリゲートには個別の型があり、静的バインディングを使用するため、通常のデリゲートをオーバーロードすることはできません。ただし、抽象クラスと動的バインディング
を使用できます。Delegate
すぐにコンパイルして実行できるソリューション (C++/CLI で記述) は次のとおりです。
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Threading;
delegate void DelegateVI (int);
delegate void DelegateVB (bool);
delegate void DelegateVAUC (array<unsigned char>^);
ref class CWorker
{
public:
void DoWork (int i_iValue)
{
Console::WriteLine ("int");
Thread::Sleep (500);
}
void DoWork (bool i_bValue)
{
Console::WriteLine ("bool");
Thread::Sleep (1000);
}
void DoWork (array<unsigned char>^ i_aucValue)
{
Console::WriteLine ("array<uc>");
Thread::Sleep (2000);
}
};
generic <class T>
ref class CData
{
public:
CData (int i_iSize, CWorker^ i_oWorker)
{
m_aData = gcnew array<T>(i_iSize);
if (T::typeid == int::typeid)
{
Reflection::MethodInfo^ oMethod = CWorker::typeid->GetMethod("DoWork", gcnew array<Type^>{int::typeid});
m_delDoWork = Delegate::CreateDelegate (DelegateVI::typeid, i_oWorker, oMethod);
}
else if (T::typeid == bool::typeid)
{
Reflection::MethodInfo^ oMethod = CWorker::typeid->GetMethod("DoWork", gcnew array<Type^>{bool::typeid});
m_delDoWork = Delegate::CreateDelegate (DelegateVB::typeid, i_oWorker, oMethod);
}
if (T::typeid == array<unsigned char>::typeid)
{
Reflection::MethodInfo^ oMethod = CWorker::typeid->GetMethod("DoWork", gcnew array<Type^>{array<unsigned char>::typeid});
m_delDoWork = Delegate::CreateDelegate (DelegateVAUC::typeid, i_oWorker, oMethod);
}
}
void DoWork (CWorker^ i_oWorker)
{
m_delDoWork->DynamicInvoke (gcnew array<Object^>{m_aData[0]});
// i_oWorker->DoWork (m_aData[0]); //--> fails with compiler error C2664: cannot convert argument...
}
array<T>^ m_aData;
Delegate^ m_delDoWork;
};
int main()
{
CWorker^ oWorker = gcnew CWorker;
CData<bool>^ oData = gcnew CData<bool>(3, oWorker);
oData->DoWork (oWorker);
}