我不喜欢那些总是说“不行”的人。;-)
因此我的答案是:可以!
起初我想从一个泛型方法中调用一个重载的非泛型方法。编译器不喜欢这样做。可能的解决方案在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]});
}
array<T>^ m_aData;
Delegate^ m_delDoWork;
};
int main()
{
CWorker^ oWorker = gcnew CWorker;
CData<bool>^ oData = gcnew CData<bool>(3, oWorker);
oData->DoWork (oWorker);
}