The delegate will be a reference to the derived class's TestMethod. Even though you're passing &BaseyClass::TestMethod
, that's a virtual method, you're also passing this
, which is the derived type, and both of those are taken into account when the delegate is created.
Other notes:
- TestMethodDelegate doesn't need to be inside the class definition. The more standard way is to have the delegate outside of the class, just in the namespace. (Or use the existing built-in one,
Action
.) - You don't need to
GCHandle::Alloc
(I assume that's what you meant by Allow). Instead, declare_testMethodHandle
asTestMethodDelegate^
(orAction^
). In general, you shouldn't need to deal with GCHandle unless you're interfacing with unmanaged code, and this code is all managed.
Here's my test code:
public ref class BaseyClass
{
public:
BaseyClass() { this->_testMethodHandle = gcnew Action(this, &BaseyClass::TestMethod); }
virtual void TestMethod() { Debug::WriteLine("BaseyClass::TestMethod"); }
Action^ _testMethodHandle;
};
public ref class DerivedClass : BaseyClass
{
public:
virtual void TestMethod() override { Debug::WriteLine("DerivedClass::TestMethod"); }
};
int main(array<System::String ^> ^args)
{
BaseyClass^ base = gcnew DerivedClass();
base->_testMethodHandle();
return 0;
}
Output:
DerivedClass::TestMethod