我不喜欢那些总是说“不,你不能”的人。;-)
因此我的回答是:是的,你可以!
最初我想从泛型方法中调用重载的非泛型方法。编译器不喜欢那样。可能的解决方案在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);
}