📄 delegates.txt
字号:
Delegates in managed C++
Chris Maunder, The Code Project (www.codeproject.com)
This sample demonstrates single- and multi-cast delegates
using C++, including declaration, creation and usage, and
a discussion on type safety.
Introduction
Delegates are .NET's type safe equivalent to function pointers.
Delegates go further than this though. Instead of a single
delegate having the ability to point to, and invoke, a single
function, delegates in .NET give you the ability to have a single
delegate point to a list of methods, each which will be called in
turn.
Creating a single cast delegate
To create a delegate you must first declare a delegate type that
has the same signature as the methods you wish it to invoke. For
instance, if we wished to have a delegate call a fuction that took
a String* as a parameter and returned an int, we might declare it
as
__delegate int MyDelegate(String *str);
To use a delegate to invoke your methods you must create an instance
of the delegate and pass in an object and the method of that object
you wish to call.
For instance, suppose we had a managed class
__gc class MyClass
{
public:
int MethodA(String *str)
{
return str->Length;
}
}
we could declare an object of type MyClass and a delegate to call the
objects methods like
MyClass *pMC = new MyClass();
MyDelegate *pDelegate = new MyDelegate(pMC, &MyClass::MethodA);
To invoke the object's method using the delegate is as simple as calling
pDelegate->Invoke("Invoking MethodA");
Creating a multi cast delegate
Multi cast delegates allow you to chain together methods so that each one
will be called in turn when the delegate is invoked. Use the static
Delegate::Combine method to combine delegates into a multicast delegate.
__gc class MyClass
{
public:
int MethodA(String *str)
{
return str->Length;
}
int MethodB(String* str)
{
return str->Length * 2;
}
};
...
MyClass *pMC = new MyClass();
MyDelegate *pDelegate = new MyDelegate(pMC, &MyClass::MethodA);
MyDelegate *pDelegate2 = new MyDelegate(pMC, &MyClass::MethodB);
MyDelegate *pMultiDelegate = static_cast<MyDelegate *>(Delegate::Combine(pDelegate, pDelegate2));
When you invoke the multicast delegate 'pMultiDelegate' it will first call
MyClass::MethodA, then MyClass::MethodB.
Type Safety
Delegates are inherintly type safe. You cannot compile calls to a delegate
using the wrong parameters, or assign the return value of a delegate to a
type that cannot be implicitely cast from the return type of the method the
delegate is calling. Because an object and method are passed to the delegates
constructor, the compiler has all the information it needs to ensure that
errors caused by mismatched parameters and return types do not occur.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -