多播委托C# [英] Multicast delegate C#
问题描述
正在学习有关委托。当我读到。我了解到,在一个委托添加多个函数被调用多播委托。在此基础上我写了一个程序。这里有两个功能(的addNumbers和MultiplyNumbers)我在MyDelegate增加。
是下面的程序是多播委托的例子?
公共部分类的MainPage:的PhoneApplicationPage
{
公众委托无效MyDelegate(int类型的,INT B) ;
//构造
公众的MainPage()
{
的InitializeComponent();
MyDelegate myDel =新的MyDelegate(的addNumbers);
myDel + =新的MyDelegate(MultiplyNumbers);
myDel(10,20);
}
公共无效的addNumbers(INT X,int y)对
{
INT总和= X + Y;
MessageBox.Show(sum.ToString());
}
公共无效MultiplyNumbers(INT X,int y)对
{
INT MUL = X * Y;
MessageBox.Show(mul.ToString());
}
}
是的,这是一个多播委托的一个例子。请注意,而不是
新MyDelegate(的addNumbers)
通常可以说只是
的addNumbers
由于所谓的方法组转换存在,将创建委托实例为您服务。
另外要注意的是,你的声明公共委托无效MyDelegate(int类型的,INT b);
不的有无的居住里面另一种类型的(这里的的MainPage
类中)。这可能是该命名空间的直接成员(因为它是一个类型)。但是,当然,它是完全有效的鸟巢成为一个类中,如你这样做,类似为什么您创建嵌套类的原因的原因。
Am studying about delegates. As I read. I learned that adding more than one function in a delegate is called multicast delegate. Based on that I wrote a program. Here two functions (AddNumbers and MultiplyNumbers) I added in the MyDelegate. Is the below program is an example for multicast delegate ?.
public partial class MainPage : PhoneApplicationPage
{
public delegate void MyDelegate(int a, int b);
// Constructor
public MainPage()
{
InitializeComponent();
MyDelegate myDel = new MyDelegate(AddNumbers);
myDel += new MyDelegate(MultiplyNumbers);
myDel(10, 20);
}
public void AddNumbers(int x, int y)
{
int sum = x + y;
MessageBox.Show(sum.ToString());
}
public void MultiplyNumbers(int x, int y)
{
int mul = x * y;
MessageBox.Show(mul.ToString());
}
}
Yes, it's an example of a multicast delegate. Note that instead of
new MyDelegate(AddNumbers)
you can typically say just
AddNumbers
because a so-called method group conversion exists that will create the delegate instance for you.
Another thing to note is that your declaration public delegate void MyDelegate(int a, int b);
does not have to reside inside another type (here inside the MainPage
class). It could be a direct member of the namespace (since it's a type). But of course it's perfectly valid to "nest" it inside a class, as you do, for reasons similar to the reason why you create nested classes.
这篇关于多播委托C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!