Download presentation
Presentation is loading. Please wait.
Published byBudi Sugiarto Salim Modified over 6 years ago
1
.NET and .NET Core: Languages, Cloud, Mobile and AI
5. Generic Delegate and Lambda Pan Wuming 2018
2
Topics Coding with Denotations Delegates
Generic to Simplify Delegate Declaration The Action and Func generic delegates Covariance and Contravariance in Generic Lambda Expressions
3
Coding with Denotations
Denoting Collection of Names Denoting Behavior Group Referring to Behaviors Enumerations Interfaces Delegates
4
Delegates Delegate types are derived from the Delegate class in the .NET Framework. Delegate types are sealed. The instantiated delegate can be passed as a parameter, or assigned to a property. The instantiated delegate can wrap an instance method or a static method
6
<Grid> <Button Content="Show" Name="ShowButton" HorizontalAlignment="Left" Height="123" Margin="52,53,0,0" VerticalAlignment="Top" Width="193" FontSize="20"/> <Button Content="Delegat to label" Name="ToLabelButton" HorizontalAlignment="Left" Margin="52,271,0,0" VerticalAlignment="Top" Width="247" Height="52" FontSize="20"/> <Button Content="Delegat to ToMessageBox" Name="ToMessageBox" HorizontalAlignment="Left" Margin="400,271,0,0" VerticalAlignment="Top" Width="315" Height="52" FontSize="20"/> <Label Content="Label" Name="ShowLabel" HorizontalAlignment="Left" Margin="345,44,0,0" VerticalAlignment="Top" Height="169" Width="384" FontSize="20"/> </Grid>
7
public delegate void TextShow(string s);
public partial class MainWindow : Window { TextShow MyShow; public MainWindow() InitializeComponent(); ShowButton.Click = ShowButtonClick; ToLabelButton.Click = ToLabelButtonClick; ToMessageBox.Click = ToMessageBoxClick; }
8
public void Show(string s)
{ ShowLabel.Content = s; } //public event RoutedEventHandler Click; //public delegate void RoutedEventHandler(object sender, RoutedEventArgs e);
9
public void ShowButtonClick(object sender, RoutedEventArgs e)
{ MyShow("Use ShowButtonClick Method!"); } public void ToMessageBoxClick(object sender, RoutedEventArgs e) MyShow = (s) => MessageBox.Show(s); public void ToLabelButtonClick(object sender, RoutedEventArgs e) //?
10
Multicasting A delegate can call more than one method when invoked
Delegates with more than one method in their invocation list derive from MulticastDelegate MulticastDelegate is a subclass of System.Delegate. To add an extra method to the delegate's list of methods To remove a method from the invocation list
11
… d1 = obj.Method1; d1 += obj.Method2; 1 2 obj.Method1 _target obj
_methodPtr MethodClass.Method1 _prev null 1 _target obj _methodPtr MethodClass.Method2 _prev _target obj _methodPtr MethodClass.Method1 _prev null obj.Method2 2
13
<Grid> <Button Content="Show" Name="ShowButton" HorizontalAlignment="Left" Height="123" Margin="52,53,0,0" VerticalAlignment="Top" Width="193" FontSize="20"/> <Button Content="Delegat to label" Name="ToLabelButton" HorizontalAlignment="Left" Margin="52,271,0,0" VerticalAlignment="Top" Width="247" Height="52" FontSize="20"/> <Button Content="Delegat to ToMessageBox" Name="ToMessageBox" HorizontalAlignment="Left" Margin="400,271,0,0" VerticalAlignment="Top" Width="315" Height="52" FontSize="20"/> <Label Content="Label" Name="ShowLabel" HorizontalAlignment="Left" Margin="345,44,0,0" VerticalAlignment="Top" Height="169" Width="384" FontSize="20"/> <Button Content="Remove to label" Name="RemoveToLabel" HorizontalAlignment="Left" Margin="52,338,0,0" VerticalAlignment="Top" Width="247" Height="52" FontSize="20"/> <Button Content="Remove to ToMessageBox" Name="RemoveToMessageBox" HorizontalAlignment="Left" Margin="400,338,0,0" VerticalAlignment="Top" Width="315" Height="52" FontSize="20"/> </Grid>
14
public delegate void DelTextShow(string s);
public partial class MainWindow : Window { public DelTextShow MyShow; DelTextShow L; DelTextShow M;
15
public MainWindow() { InitializeComponent(); ShowButton.Click += ShowButtonClick; ToLabelButton.Click += ToLabelButtonClick; ToMessageBox.Click += ToMessageBoxClick; L = ShowToLable; M = (s) => MessageBox.Show(s); RemoveToLabel.Click += RemoveToLabelClick; RemoveToMessageBox.Click += RemoveToMessageBoxClick; }
16
public void ShowToLable(string s)
{ ShowLabel.Content = s; } //public event RoutedEventHandler Click; //public delegate void RoutedEventHandler(object sender, RoutedEventArgs e);
17
public void ShowButtonClick(object sender, RoutedEventArgs e)
{ try MyShow("Use ShowButtonClick Method!"); } catch ShowLabel.Content = "Label"; } } public void ToMessageBoxClick(object sender, RoutedEventArgs e) MyShow += M; public void ToLabelButtonClick(object sender, RoutedEventArgs e) MyShow += L;
18
public void RemoveToLabelClick(object sender, RoutedEventArgs e)
{ MyShow -= L; } public void RemoveToMessageBoxClick(object sender, RoutedEventArgs e) MyShow -= M;
19
Generic to Simplify Delegate Declaration
Problem: It does not necessary to assign different name to delegates Generics as "code template“ to define delegates in advance in class library Generics The runtime knows what type of data structure you are using and can store it in memory more efficiently. List<int> ListGeneric = new List<int> { 5, 9, 1, 4 };
20
public delegate void TextShow(string s);
public delegate void DelTextShow(string s); public partial class AClass { public DelTextShow MyShow; public TextShow MyShowNew; public AClass() MyShow = (s) => MessageBox.Show(s); MyShowNew = (s) => MessageBox.Show(s); }
21
The Action and Func generic delegates
A delegate can define its own type parameters. In and out Generic Modifier public delegate void Action<in T1, in T2>(T1 arg1,T2 arg2); public delegate TResult Func<in T1, out TResult>(T1 arg1);
22
public delegate void DelTextShow(string s);
public partial class MainWindow : Window { public DelTextShow MyShow; DelTextShow L; DelTextShow M; public partial class MainWindow2 : Window { Action<string> MyShow; Action<string> L; Action<string> M;
23
The Action Generic Delegates in .NET Framework Class Library
Description Action Encapsulates a method that has no parameters and does not return a value. Action< T> Encapsulates a method that has a single parameter and does not return a value. Action< T1, T2> Encapsulates a method that has two parameters and does not return a value. ... Action< T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> Encapsulates a method that has 15 parameters and does not return a value. Action< T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> Encapsulates a method that has 16 parameters and does not return a value.
24
The Func Generic Delegates in .NET Framework Class Library
Description Func< TResult> Encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter. Func< T, TResult> Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter. Func< T1, T2, TResult> Encapsulates a method that has two parameters and returns a value of the type specified by the TResult parameter. ... Func< T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult> Encapsulates a method that has 16 parameters and returns a value of the type specified by the TResult parameter.
25
Covariance and Contravariance
Covariance: Enables you to use a more specific type than originally specified. Contravariance: Enables you to use a more generic (less derived) type than originally specified. Invariance: Means that you can use only the type originally specified The in keyword specifies that the type parameter is contravariant. The out keyword specifies that the type parameter is covariant.
26
Contravariance class GenericDelegate { public GenericDelegate()
Action<BaseClass> b = (target) => target.Write(); }; Action<DerivedClass> d = b; d(new DerivedClass()); Action<DerivedClass> e = (target) => target.DerivedClassWrite(); e(new DerivedClass()); //Action<BaseClass> f = e; } class BaseClass { public void Write() Console.WriteLine("BaseClassWrite"); } class DerivedClass : BaseClass public void DerivedClassWrite() Console.WriteLine("DerivedClassWrite"); 语法错误。
27
Actual passing and assigning direction is contravariant !
课堂演练: 将前述代码中 Action 改为 Func,修改代码,以使能够运行。 Actual passing and assigning direction is contravariant !
28
Lambda Expressions Anonymous Methods The lambda operator =>
Specifying input parameters (if any) on the left side of => Putting the expression or statement block on the other side Lambdas can refer to outer variables
29
public void MethodA(int input)
{ int j = 0; Func<bool> del = () => { j = 10; return j > input; }; Func<bool> del1 = () => j > input; Func<int,bool> del2 = (x) => { return x == j; }; MethodB(() => j > input); } public void MethodB(Func<bool> delIn) { }
30
Calling lambda expression will change the values of variables!
在C# interactive 中执行如下代码 > int j = 0; Func<bool> del = () => { j = 10; return j > 6; }; del(); Console.WriteLine(j.ToString()); 10 Calling lambda expression will change the values of variables!
31
> class ClassB . { . public Func<bool> MethodA(int k) { int j = 0; Func<bool> del = () => {return j > k; }; return del; } public void MethodB(Func<bool> delB) Console.WriteLine(delB().ToString()); . } . var c = new ClassB(); . c.MethodB(c.MethodA(5)); False
32
> class ClassB . { . public Func<bool> MethodA(int k) { int j = 0; Func<bool> del = () => {return j > k; }; j = 10; return del; } public void MethodB(Func<bool> delB) Console.WriteLine(delB().ToString()); . } . var c = new ClassB(); . c.MethodB(c.MethodA(5)); True
33
Summarizing the Applications of Delegates
Callback Function Event members in a Type Replace simple Interface implementation
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.