Delegates and Lambda Expressions notes
Delegate: pointer to a function
Eg. Photo class -> Load and Save methods
Photofilters -> Contains different types of filters. Eg., BWFilter, Contrast, Brightness, Resize etc
PhotoProcessor -> Takes the path, loads a photo, applies some filters and saves the Photo.
If a developer wants to develop a new filter, he has to download the code, create the filter and then make changes to PhotoProcessor.
Instead of PhotoProcessor taking the actual filters class, will take a PhotoFilterHandler delegate and will take as parameter.
public delegate PhotoFilterHandler(Photo photo);
public Photo process(string path, PhotoFilterHandler filter){
photo.Load(path);
filter(photo);
photo.Save();
}
while implementing it
create an instance photoprocessor class.
Create an instance of PhotoFilterHandler
var filterHandler = photoFilter.ApplyBWFilter;
filterHandler += photoFilter.ApplyBrightnessFilter;
filterHandler += Resize;
photoProcessor.process("c:\\photos\\photo1.png", filterHandler);
static void Resize(Photo photo){
Console.WriteLine("Apply Resize");
}
Lambda Expressions
args => expression
No arguments
() => expression
One argument
x => expression
Two or more
(x, y, z) => expression
Action<> and Func<> are delegates
Action only input
Func<int, int>
A function taking an integer as argument and returning an int as output.
Comments
Post a Comment