什么是asp.net中的委托 [英] what is delegate in asp.net

查看:75
本文介绍了什么是asp.net中的委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


推荐答案

委托是对函数的引用,就像TextBox变量是一样.对出现在屏幕上的TextBox实例的引用.

它们出奇的方便:您可以使用它们编写可以在各种目标环境下工作的代码,而无需更改代码.例如,您可以编写一个带委托的Print方法:
A Delegate is a reference to a function, in the same way that a TextBox variable is a reference to teh instance of a TextBox that appears on the screen.

They are surprisingly handy: you can use them to write code that can work to a variety of destinations without changing the code. For example, you could write a Print method that took a delegate:
private void DoPrint()
    {
    string text = "hello world!";
    Print(text, PrintConsole);
    Print(text, PrintTextbox);
    }
private void PrintConsole(string s)
    {
    Console.WriteLine("Console: " + s);
    }
private void PrintTextbox(string s)
    {
    myTextBox.Text = "TextBox: " + s;
    }
private delegate void printDestination(string s);
private void Print(string s, printDestination pd)
    {
    pd("From Print: " + s);
    }

您可以完全更改文本所发生的变化,而无需更改Print方法中的代码.

还有很多其他用途,但这是一般的想法.

You can completely change what happens to the text without changing the code in the Print method.

There are a lot of other uses, but that''s the general idea.


我不确定您是否可能看过以下内容.这两个是等效的:

I am not sure if you may have seen the following. These two are equivalent:

datePicker.Loaded += (s, a) =>
{
    var textBox1 = (TextBox)datePicker.Template.FindName("PART_TextBox", datePicker);
    textBox1.Background = datePicker1.Background;
};

datePicker.Loaded += delegate
{
    var textBox1 = (TextBox)datePicker.Template.FindName("PART_TextBox", datePicker);
    textBox1.Background = datePicker1.Background;
};



这两个都使用RoutedEventHandler委托:



Both these use the RoutedEventHandler delegate:

public delegate void RoutedEventHandler(object sender, RoutedEventArgs e);



您还可以执行以下操作



You could also do the following

void datePicker_Loaded(object sender, RoutedEventArgs e)
{
    var textBox1 = (TextBox)datePicker.Template.FindName("PART_TextBox", datePicker);
    textBox1.Background = datePicker1.Background;
}



那么您可以将处理程序分配为:



then you would assign the handler as:

DatePicker.Loaded += new RoutedEventHandler(datePicker1_Loaded);







or

DatePicker.Loaded += datePicker1_Loaded;


通常,委托与C ++函数指针相似.
Generally Delegates are Similar to C++ Function Pointers.


这篇关于什么是asp.net中的委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆