Advertisement
ivandrofly

Delegates

Jul 25th, 2015
419
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.72 KB | None | 0 0
  1. using System;
  2. delegate double Function(double x);
  3. class Multiplier
  4. {
  5.     double factor;
  6.     public Multiplier(double factor) {
  7.         this.factor = factor;
  8.     }
  9.     public double Multiply(double x) {
  10.         return x * factor;
  11.     }
  12. }
  13. class Test
  14. {
  15.     static double Square(double x) {
  16.         return x * x;
  17.     }
  18.     static double[] Apply(double[] a, Function f) {
  19.         double[] result = new double[a.Length];
  20.         for (int i = 0; i < a.Length; i++) result[i] = f(a[i]);
  21.         return result;
  22.     }
  23.     static void Main() {
  24.         double[] a = {0.0, 0.5, 1.0};
  25.         double[] squares = Apply(a, Square);
  26.         double[] sines = Apply(a, Math.Sin);
  27.         Multiplier m = new Multiplier(2.0);
  28.         double[] doubles =  Apply(a, m.Multiply);
  29.     }
  30. }
  31. // Souce: CSharp Language Specification
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement