static void Delegates() { // Delegates are objects that knows how to call a method (or a group of methods) // It is also a reference to a function // We use delegates to achieve extensibility and flexibility (eg.: frameworks) // Interfaces or Delegates??? // Use a Delegate when: // - An eventing design pattern is used // - The caller doesn't need to access other properties or methods on the object implementing the method var processor = new PhotoProcessor(); var filters = new PhotoFilters(); var newFilters = new NewPhotoFilters(); // Dotnet has its own delegates. So, we do not need to create ours // PhotoProcessor.PhotoFilterHandler filterHandler = filters.ApplyBrightness; Action <Photo> filterHandler = filters.ApplyBrightness; filterHandler += filters.ApplyContrast; filterHandler += filters.Resize; filterHandler += newFilters.RemoveRedEye; processor.Process("photo.jpg", filterHandler); }
// public delegate TResult Func<in T1,in T2, out TResult>(T1 arg1,T2 arg2); static void Main(string[] args) { int number1 = 5; // Lamba Func <int, int> squareOfNumber = i => number1 * number1; Console.WriteLine(squareOfNumber); var lambaDemo = new LambaDemo(); var listOFBooks = lambaDemo.GetBooks().Where(x => x.Price < 10).ToList(); Func <int, int, int> add = Sum; Func <int, int, int> minus = Subtract; int result = minus(5, 3); Console.WriteLine(result); var _doorProcessor = new UnlockDoorProcessor(); var _door = new Door(); _door.KeyNumber = "MY121HN"; Func <Door, string> processor1 = _doorProcessor.UnclockDoor; processor1 += OpenDoorWithRemote; var dd = processor1(_door); Console.ReadLine(); var processor = new PhotoProcessor(); var filters = new PhotoFilters(); Action <Photo> filterHandler = filters.ApplyBrightness; filterHandler += CustomerFilter; filterHandler += filters.ApplyContrast; filterHandler += filters.Resize; processor.Process("hhh", filterHandler); var nullable = new Nullables <int>(); var genericInitializerObject = new GenericInitializerObject <Student>(); var student = genericInitializerObject.CreateInitializerObjectGeneric(); student.Name = "Sazi"; student.Surname = "Nyathi"; var results = nullable.GetVaueOrDefault(); var number = new GenericList <int>(); number.Add(10); var students = new GenericList <Student>(); students.Add(student); var studentDictinary = new GenericDictionary <int, Student>(); studentDictinary.Add(1, student); }
public void Setup() { this.filterHandler = null; this.filters = new PhotoFilters { }; this.processor = new PhotoProcessor { }; }
//这样简洁了很多,同样Main()中对委托实例化的部分也要改,如 static void Main(string[] args) { var processor = new PhotoProcessor(); var filters = new PhotoFilters(); Action<Photo> filterHandler = filters.ApplyBrightness; //直接这样就能实例化委托,其他不用改变 filterHandler += filter.ApplyContrast; processor.Process("C:\photo.jpg", filterHandler); }
public Form1() { InitializeComponent(); filter = new PhotoFilters(this); zoomValue = 1; Picture = new Bitmap(pictureBox1.Image); DrawBool = false; DrawBool2 = false; elo = pictureBox1.CreateGraphics(); Console.WriteLine(Math.Sin(0.25 * Math.PI)); }
public static void UseDelegate() { var photoProc = new PhotoProcessor(); var filters = new PhotoFilters(); Action <Photo> filterHandler = filters.ApplyBrightness; filterHandler += filters.ApplyContrast; filterHandler += RemoveRedEye; photoProc.Process("photo.jpg", filterHandler); }
static void UsingDelegates() { var processor = new PhotoProcessor(); var filters = new PhotoFilters(); Action <Photo> filterHandler = filters.ApplyBrightness; filterHandler += filters.ApplyContrast; filterHandler += RemoveRedEyeFilter; processor.Process("photo.jpg", filterHandler); }
public void PhotoProcessorTest1() { PhotoFilters photoFilters = new PhotoFilters(); Func <Photo, string> photoFilterHandler = photoFilters.ApplyBrightness; photoFilterHandler += photoFilters.ApplyContrast; photoFilterHandler += photoFilters.Resize; photoFilterHandler += this.RemoveRedEyeFilter; Assert.Equal(expected: "Applying brightness,Applying contrast,Resizing photo,Remove red eye,", actual: new PhotoProcessor().Process(new Photo(), photoFilterHandler)); }
static void Main(string[] args) { var processor = new PhotoProcessor(); var photoFilters = new PhotoFilters(); Action <Photo> handler = photoFilters.ApplyBrightness; handler += photoFilters.ApplyContrast; handler += photoFilters.Resize; handler += CustomFilter; processor.Process("photo.jpeg", handler); }
public void Process(string path, PhotoProcessorHandler processorHandler) { var photo = Photo.Load(path, new MemoryStream()); var filters = new PhotoFilters(); //filters.ApplyBrightness(photo); //filters.ApplyContrast(photo); //filters.Resize(photo); processorHandler(photo); photo.Save(); }
static void Main(string[] args) { var processor = new PhotoProcessor(); var photoFilters = new PhotoFilters(); //PhotoProcessor.PhotoFilterHandler filterHandler = photoFilters.ApplyBrightness; Action <Photo> filterHandler = photoFilters.ApplyBrightness; filterHandler += photoFilters.ApplyContrast; filterHandler += photoFilters.Resize; filterHandler += RemoveRedEyes; processor.Process("photo.jpeg", filterHandler); }
//public string[] Filter { get; set; } public void Delegates() { var processor = new PhotoProcessor(); var filters = new PhotoFilters(); var p = new Photo(); //p.PhotoMessage = "Applying Filters"; //p.PhotoMessage += _NewLine; TextAreaBody = "Adding Filters to filterHandler Delegate \n"; PhotoProcessor.PhotoFilterHandler filterHandler = filters.AppllyBrightness; filterHandler += filters.ApplyContrast; filterHandler += RemoveRedEyeFilter; TextAreaBody += p.PhotoMessage; TextAreaBody += "Running Photo Processor to process filters \n"; TextAreaBody = processor.Process("photo.jpg", filterHandler, TextAreaBody); }
static void Main(string[] args) { Book csBook = new Book { Isbn = "1212", Title = "C#_Advanced" }; var numbers = new GenericList <int>(); numbers.Add(10); var books = new GenericList <Book>(); books.Add(new Book()); var dict = new GenericDictionary <string, Book>(); dict.Add("1234", new Book()); var NewNumber = new GenericClasses.Nullable <int>(); Console.WriteLine("Has Value? " + NewNumber.HasValue); Console.WriteLine("The value is: " + NewNumber.GetValueOrDefaultValue()); string ppath = string.Format("C:\\Users\\Mia\\Desktop\\AspNet_Practice\\Pjs\\C#NextLevel\\c#Generics_Delegate\\Generic-Delegate_solu\\Generic-Delegate\\imgs\\sun.png"); // Normal way apply filter /* PhotoProcessor pp = new PhotoProcessor(); * pp.ProcessPhoto(ppath); */ // Delegate Way to do Filter PhotoFilters pf = new PhotoFilters(); PhotoProcessor pp = new PhotoProcessor(); // Apply build-in Delegate System.Action<T> Action <Photo> FilterHandler = pf.ApplyBrightness; FilterHandler += pf.Resize; FilterHandler += ApplyNewFilter; pp.PhotoProcess(ppath, FilterHandler); Console.WriteLine("Press Enter to Quite..."); while (Console.ReadKey().Key != ConsoleKey.Enter) { } }
public static void RunDelegate() { var processor = new PhotoProcessor(); PhotoFilters filters = new PhotoFilters(); // these are like callback functions that will be passed // on the filterHandler call inside the process function // similar to js callback functions Action <Photo> filterHandler = filters.ApplyBrightness; // add another delegate filterHandler += filters.ApplyContrast; filterHandler += RemoveRedEyeFilter; processor.Process("photo.jpeg", filterHandler); }
static void Main(string[] args) { //-------------------------Delegate Start----------------------------- //var processor = new PhotoProcessors(); //var filters = new PhotoFilters(); //PhotoProcessors.PhotoFilterHandler filterHandler = filters.ApplyBrightness; //filterHandler += filters.ApplyContrast; var processor = new PhotoProcessorsAction(); var filters = new PhotoFilters(); Action <Photo> filterHandler = filters.ApplyBrightness; filterHandler += filters.ApplyContrast; processor.Process("photo.jpg", filterHandler); //---------------------------Delegate End----------------------------- //---------------------------Lambda Start----------------------------- Func <int, int> result = square => square * square; Console.WriteLine(result(5)); //---------------------------Lambda End----------------------------- //---------------------------Event Start----------------------------- Video video = new Video() { Title = "Video 1" }; var videoEncoder = new VideoEncoder(); var mailService = new MailService(); var messageService = new MessageService(); videoEncoder.VideoEncoded += mailService.OnVideoEncoded; videoEncoder.VideoEncoded += messageService.OnVideoEncoded; videoEncoder.Encode(video); //---------------------------Event End----------------------------- //---------------------------Extension Method Start----------------------------- string message = "I'm selfish, impatient and a little insecure. I make mistakes, I am out of control and at times hard to handle. But if you can't handle me at my worst, then you sure as hell don't deserve me at my best."; var shortMessage = message.Shorten(5); Console.WriteLine(shortMessage); //---------------------------Extension Method End----------------------------- }
static void Main(string[] args) { var processor = new PhotoProcessor(); PhotoProcessor.PhotoFilterHandler filterHandler; PhotoFilters filters = new PhotoFilters(); filterHandler = filters.ApplyBrightness; MyCustomFilter myCustomFilter = new MyCustomFilter(); filterHandler += myCustomFilter.MyCustomFilterMethod; processor.Process("path da foto", filterHandler); Console.Read(); }
public void Execute() { /* * An object that knows how to call a method (or a group of methods) * A reference to a function * For designing extensible and flexible applications */ var processor = new PhotoProcessor(); var filters = new PhotoFilters(); PhotoProcessor.PhotoFilterHandler filterHandler = filters.ApplyBrightness; filterHandler += filters.Resize; filterHandler += FilterOutsidePhotoFilter; processor.Process("C:\\Photos\\phot.jpg", filterHandler); Action <Photo> actionFilterHanlder = filters.ApplyContrast; processor.ProcessGenericDelegate("picture.jpg", actionFilterHanlder); }
static void Main(string[] args) { Console.Write("Enter a Number: "); string userInput = Console.ReadLine(); Console.WriteLine("Your Number is: {0}", userInput); var dictionary = new Dictionary <string, string>(); dictionary["apple"] = "A fruit or a computer company"; Console.WriteLine(dictionary["apple"]); var someList = new List <int>(); someList.Add(1); someList.Add(2); someList.Add(3); someList.Add(5); someList.Add(8); someList.Add(11); someList.RemoveAt(0); someList.RemoveAt(2); for (int i = 0; i < someList.Count; i++) { Console.WriteLine(someList[i]); } foreach (int number in someList) { Console.WriteLine(number); } someList.ForEach(number => Console.WriteLine(number)); someList.ForEach(Console.WriteLine); string[] names = { "John", "Daryl", "Mike", "Sarah", "Michele" }; string[] moreNames = new string[5]; moreNames[0] = "John"; moreNames[1] = "Daryl"; Console.WriteLine("Size of names: {0}\nSize of moreNames: {1}", names.Length, moreNames.Length); // and so on string student = "John Smith"; char firstCharacter = student[1]; // ---- Exercise for loops ---- var animals = new List <string>(); animals.Add("Lion"); animals.Add("Tiger"); animals.Add("Bird"); animals.Add("Cat"); animals.Add("Dog"); animals.Add("Leopard"); string favoriteAnimal = "Bird"; foreach (string animal in animals) { Console.WriteLine(animal); } if (animals.Contains(favoriteAnimal)) { Console.WriteLine("I love {0} and also every other animal, including {1}", favoriteAnimal, animals[2]); // same as the above line, but without the placeholder Console.WriteLine("I love " + favoriteAnimal + "and also every other animal, including " + animals[2]); } else { Console.WriteLine("No, I don't care for those"); } // dictionary looping var person = new Dictionary <string, int>(); person.Add("Joan", 22); person.Add("Daniel", 42); person.Add("Anna", 34); // person = {Joan=22, Daniel=42, Anna=34} // loop through the hash map and return each key/value pair for (int i = 0; i < person.Count; i++) { Console.WriteLine("Key: {0}, Value: {1}", person.Keys.ElementAt(i), person[person.Keys.ElementAt(i)]); } foreach (var peep in person) { // print out the key (their name) and their value Console.WriteLine("Name: {0}, Age: {1}", peep.Key, peep.Value); } var studentData = new Dictionary <string, string>(); studentData["name"] = "Fred"; studentData["age"] = "20"; studentData["hometown"] = "Seattle"; studentData["favorite_food"] = "Pizza"; Console.WriteLine("This is {0}", studentData["name"]); Console.WriteLine("They are {0} years old", studentData["age"]); Console.WriteLine("from {0}", studentData["hometown"]); Console.WriteLine("and their favorite food is {0}", studentData["favorite_food"]); var students = new Dictionary <string, Dictionary <string, string> >(); students["Fred"] = new Dictionary <string, string>(); students["Fred"].Add("name", "Fred"); students["Fred"].Add("age", "20"); students["Fred"].Add("hometown", "Seattle"); students["Fred"].Add("favorite_food", "Pizza"); Console.WriteLine("This is {0}", students["Fred"]["name"]); var students2 = new Dictionary <string, Student>(); var someStudent = new Student("Fred", 20, "Seattle", "Pizza"); students2.Add("Fred", someStudent); var anotherStudent = new Student("Sally", 21, "Columbus", "Pasta"); students2.Add("Sally", anotherStudent); var studentWithNoData = new Student(); var sedan = new Car("blue", 4); sedan.Start(); sedan.Stop(); sedan.Drive(); Console.WriteLine("Car color: {0}", sedan.Color); Console.WriteLine("Number of Doors: {0}", sedan.NumberOfDoors); var coup = new Car("red", 2); var compact = new Car("blue"); Car.Compare(sedan, new Car()); int maxDoors = Car.MAX_DOORS; coup.Type = CarType.SPORTY; coup.NumberOfDoors = 4; if (coup == sedan) { Console.WriteLine("not sure how, but a coup and sedan are the same?"); } if (coup.Equals(sedan)) { Console.WriteLine(""); } Console.WriteLine(coup.ToString()); var vehicle = new Vehicle(); var genericAnimal = new Animal(0, "amoeba"); genericAnimal.Announce(); var bear = new Bear(1, "Yogi", 9999); bear.Announce(); var vehicles = new List <Vehicle>(); vehicles.Add(new Truck()); vehicles.Add(sedan); vehicles.Add(coup); vehicles.Add(compact); var vehicles2 = new List <IVehicle>(); var rallyCar = new RallyCar(); vehicles2.Add(new Truck()); vehicles2.Add(new Motorcycle()); vehicles2.Add(sedan); vehicles2.Add(coup); vehicles2.Add(compact); vehicles2.Add(rallyCar); var crossOver = new CrossOver(); // this won't work, because crossover doesn't implement // the IVehicle interface //vehicles2.Add(crossOver); foreach (var v in vehicles2) { v.Accelerate(10); } Drive(rallyCar); Drive(sedan); Drive(new Truck()); var pupil = new Student("John Smith", 19, "Columbus", "Pizza"); var teacher = new Teacher("Jane Doe", 31); PrintInfo(pupil); PrintInfo(teacher); // Page 21 in interfaces and extension methods example Console.WriteLine("-----------------------"); var dbMigrator = new DbMigrator(new ConsoleLogger()); var dbMigrator2 = new DbMigrator(new FileLogger("migrator.log")); dbMigrator.Migrate(); dbMigrator2.Migrate(); Console.WriteLine("-----------------------"); // event stuff (week 6 day 2) ProcessBusinessLogic bl = new ProcessBusinessLogic(); bl.ProcessCompleted += bl_ProcessCompleted; // register with an event bl.ProcessCompleted += bl_ProcessUpdated; bl.StartProcess(); var myProcess = new PhotoProcessor(); var filters = new PhotoFilters(); Action <Photo> filterHandler = filters.ApplyContrast; filterHandler += filters.ApplyBrightness; filterHandler += RemoveRedEyeFilter; myProcess.Process("pic.jpg", filterHandler); // lambda function takes in a number and then squares it Func <int, int> squareFunction = num => num * num; // in our case, it passes in 3 and returns 9 Console.WriteLine(squareFunction(3)); const int factor = 5; Func <int, int> multiplier = num => num * factor; int result = multiplier(10); Console.WriteLine(multiplier(6)); Console.WriteLine(result); Func <int, int, int, double> pythagoreanTheorem = (a, b, c) => Math.Pow(a, 2) + Math.Pow(b, 2) + Math.Pow(c, 2); double result2 = pythagoreanTheorem(1, 2, 3); Console.WriteLine(pythagoreanTheorem(2, 3, 4)); Console.WriteLine(result2); var library = new BookRepository(); List <Book> books = library.Books; List <Book> cheapBooks = books.FindAll(book => book.Price < 10); foreach (var book in cheapBooks) { Console.WriteLine(book.Title); } Console.ReadKey(); }
public static void Main(string[] args) { #region Generics Console.WriteLine("------- Starting Generics ---------"); var number = new Nullable <int>(0); Console.WriteLine("Has Value: " + number.HasValue); Console.WriteLine("Value: " + number.GetValueOrDefault()); #endregion #region Delegates Console.WriteLine("------- Starting Delegates ---------"); // Use for extesibility and flexibility var processor = new PhotoProcessor(); var photoFilters = new PhotoFilters(); Action <Photo> filterHandler = photoFilters.ApplyBrightness; filterHandler += photoFilters.ApplyContrast; filterHandler += RemoveRedEye; processor.Process("Photos.jpg", filterHandler); #endregion #region Lambda Expressions Console.WriteLine("------- Starting Lambda Expressions ---------"); const int factor = 5; Func <int, int> multiplier = num => num * factor; Console.WriteLine("The result after multiplication: " + multiplier(50)); var books = new BookRepository().GetBooks(); var cheapBooks = books.FindAll(b => b.Price <= 35); Console.WriteLine("Books having the price less than 35: "); foreach (var book in cheapBooks) { Console.WriteLine(book.Title); } #endregion #region Extension Methods Console.WriteLine("------- Starting Extension Methods ---------"); string post = "This is supposed to be a very long post blah blah blah"; //Our extension method var shortenedPost = post.Shorten(5); Console.WriteLine(shortenedPost); //Pre-defined extension method IEnumerable <int> numbers = new List <int>() { 1, 5, 3, 10, 18, 9, 34, 12 }; Console.WriteLine("The maximum number from the list:" + numbers.Max()); #endregion #region LINQ Console.WriteLine("------- Starting LINQ ---------"); // LINQ Query Operators var cheapBooksAgain = from b in books where b.Price < 30 orderby b.Title select b.Title; // LINQ Extension Methods cheapBooksAgain = books .Where(b => b.Price < 30) .OrderBy(b => b.Title) .Select(b => b.Title); Console.WriteLine("Books having price less than 30$: "); foreach (var book in cheapBooksAgain) { Console.WriteLine(book); } var lastThreeBooks = books.Skip(2).Take(3); Console.WriteLine("Last three books: "); foreach (var book in lastThreeBooks) { Console.WriteLine(book.Title); } #endregion #region Events and Delegates Console.WriteLine("------- Starting Events and Delegates ---------"); var video = new Video() { Title = "Video 1" }; var videoEncoder = new VideoEncoder(); // Publisher var mailService = new MailService(); // Subscriber var messageService = new MessageService(); // Subscriber videoEncoder.VideoEncoded += mailService.OnVideoEncoded; // Binding the event videoEncoder.VideoEncoded += messageService.OnVideoEncoded; // Binding the event videoEncoder.Encode(video); #endregion #region Dynamic Console.WriteLine("------- Starting Dynamic ---------"); //Normal way object obj = "Ubaid"; //With Reflection //var methodInfo = obj.GetType().GetMethod("GetHashCode"); //methodInfo.Invoke(null, null); //With Dynamic dynamic testInt = 10; //Although optimize is not defined, still no compile time error if you uncomment //excelObject.Optimize(); dynamic testSecondInt = 20; object result = testInt + testSecondInt; Console.WriteLine("The result: " + result.GetType()); #endregion #region Exception Handling Console.WriteLine("------- Starting Exception Handling ---------"); try { var a = 1; var b = 0; //var answer = a / b; var api = new YoutubeApi(); var videos = api.GetVideos(); } catch (DivideByZeroException ex) { Console.WriteLine("You can't divide by 0"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine("Argument is out of range."); } catch (Exception ex) { Console.WriteLine("Exception Message: " + ex.Message); Console.WriteLine("Inner Exception Message: " + ex.InnerException.Message); } #endregion #region Async and Await var download = new Download(); download.DownloadHtml("https://msdn.microsoft.com"); #endregion }
static void Main(string[] args) { //Exception Hnadeling StreamReader streamReader = null; try { streamReader = new StreamReader(@"c:\test.zip"); var content = streamReader.ReadToEnd(); throw new Exception("!"); } catch (Exception ex) { Console.WriteLine("Error Occurred!"); } finally { if (streamReader != null) { streamReader.Dispose(); } } ///Or /// StreamReader streamReader = null; try { //using (var StreamReader = new StreamReader(@"c:\test.zip")) //{ // var content = streamReader.ReadToEnd(); //} var youtube = new YouTubeApi(); var vids = youtube.GetVideos("user"); } catch (Exception ex) { Console.WriteLine(ex.Message); } //Dynamics dynamic dynamic = "test"; dynamic = 10; dynamic a = 10; dynamic bbb = 5; var c = a + bbb; int d = a; long e = d; //Nullables DateTime?date = null; Console.WriteLine(date.GetValueOrDefault()); Console.WriteLine(date.HasValue); //Console.WriteLine(date.Value); DateTime date2 = date.GetValueOrDefault(); DateTime?date3 = date2; ///Linq Extension Methods var books1 = new BookRepository().GetBooks(); var cheapBooks1 = books1.Where(x => x.Price < 10).OrderBy(x => x.Title); //Linq Query Operator var cheaperBooks = from b in books1 where b.Price < 10 orderby b.Title select b.Title; //Extensions string post = "this is long long long post..."; var shortenedPost = post.Shorten(3); Console.WriteLine(shortenedPost); //Events var video = new Video() { Title = "Video Title 1" }; var videoEncoder = new VideoEncoder(); /// Publisher var mailService = new MailService(); // subscriber var messageService = new MessageService(); videoEncoder.videoEncoded += mailService.OnVideoEncoded; videoEncoder.videoEncoded += messageService.OnVideoEncoded; videoEncoder.Encode(video); // => const int factor = 5; Func <int, int> multipler = n => n * factor; Console.WriteLine(multipler(5)); var books = new BookRepository().GetBooks(); //var cheapBooks = books.FindAll(IsCheaperThan10Dollars); var cheapBooks = books.FindAll(b => b.Price < 10); foreach (var book in cheapBooks) { Console.WriteLine(book.Title); } //Delegates var photo = new PhotoProcessor(); var filters = new PhotoFilters(); //PhotoProcessor.PhotoFilterHandler filterHandler = filters.ApplyBrightness; Action <Photo> filterHandler = filters.ApplyBrightness; filterHandler += filters.ApplyContrast; filterHandler += RemoveRedEyeFilter; photo.Process("test", filterHandler); //Generics var numbers = new Generic <int>(); numbers.Add(10); var dictionary = new GenericDictionary <string, Book>(); dictionary.Add("1", new Book()); var NUMBER = new AdvancedTopics.Nullable <int>(); Console.WriteLine("Has Value? " + NUMBER.HasValue); Console.WriteLine("Value: " + NUMBER.GetValueOrDefault()); //Or You can use System.Nullable for this purpose. }