static void Main(string[] args) { int[] sample = { 1, 2, 3, 5, (int)(Math.Pow(Math.E, 2) + 1) }; Console.Out.WriteLine("Исходный массив:"); print(sample); Console.Out.WriteLine("После обработки статическим методом:"); print(map(sample, Pow)); IntOperation Ln = delegate(int value) { return((int)Math.Log(value)); }; Console.Out.WriteLine("После обработки анонимным методом:"); print(map(sample, Ln)); Console.Out.WriteLine("После обработки лямбда-выражением:"); print(map(sample, (int value) => { int a = 0, b = 1; for (int i = 0; i < value; i++) { int temp = a; a = b; b = temp + b; } return(a); })); Console.In.Read(); }
static void Main(string[] args) { IPerson p = new Person("Wekoslav", "Stefanovski"); PrintFullName(p); SingleIntOperation square = x => x * x; SingleIntOperation cube = x => x * x * x; IntOperation add = (x, y) => x + y; IntOperation sub = (x, y) => x - y; IntOperation mul = (x, y) => x * y; IntOperation div = (x, y) => x / y; TakeTwoListsAndOperate addTwoLists = (first, second) => from f in first from s in second select f + s; ExecOperation(add); ExecOperation(Substraction); ExecOperation(p.Length); SaveOperation(p.Length); p = null; Console.WriteLine(savedOp(0, 0)); var p2 = new Person("Ivan", "Acev"); ExecOperation(p2.Length); }
public static void ChangeListValues(ref List <int> list, IntOperation op) { for (int i = 0; i < list.Count; i++) { list[i] = op(list[i]); } }
private void button1_Click(object sender, EventArgs e) { IntOperation res = new IntOperation(Start); if (checkBox1.Checked) { res += op1; //textBox1.Text = res.ToString(); //label1.Text = res(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text)).ToString(); } if (checkBox2.Checked) { res += op2; //textBox1.Text = res.ToString(); } if (checkBox3.Checked) { res += op3; //textBox1.Text = res.ToString(); } if (checkBox4.Checked) { res += op4; //textBox1.Text = res.ToString(); } label1.Text = res(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text)).ToString(); //label1.Text = Convert.ToString(res); }
private static void DelegatePresentation() { var a = 3; var b = 2; IntOperation operation = new IntOperation(SomeFunction); //operation = SomeFunction; //or this //operation = Math.Min; // or this var ret = operation.Invoke(a, b); //var ret2 = operation(a, b); //shorter version Console.WriteLine("Sum on {0} and {1} is {2}", a, b, ret); operation = Math.Max; ret = operation.Invoke(a, b); //subtraction Console.WriteLine("Max on {0} and {1} is {2}", a, b, ret); Func <int, int, int> func = SomeFunction; //new SomeFunction<int, int, int>(operation); Action <string> action = Print; _action = action; action("Text"); //subscribing to delegate - works only with void delegates action += s => { Console.WriteLine("1"); }; action += s => { Console.WriteLine("s2"); }; action(""); ExecuteDelegate(operation); }
public void Lambda() { IntOperation addOperation = (a, b) => a + b; IntOperation subOperation = (a, b) => a - b; Console.WriteLine(addOperation(5, 5)); Console.WriteLine(subOperation(5, 5)); }
public Form1() { InitializeComponent(); op1 = Form1.Sum; op2 = Form1.Min; op3 = Form1.Mul; op4 = Form1.Div; }
private void demoButton_Click(object sender, EventArgs e) { int result; IntOperation Square = x => x * x; result = Square(5); MessageBox.Show("5 squared is " + result.ToString()); }
static void Main() { IntOperation op1 = new IntOperation(Sum); int result = op1(5, 10); //15 op1 = new IntOperation(Mul); //op1 = Mul result = op1(5, 10); //50 }
static void Main(string[] args) { var op = new IntOperation(Add); Console.WriteLine(op(2, 2)); op = Subtract; Console.WriteLine(op(3, 2)); }
public static void main() { var op = new IntOperation(Add); Console.WriteLine(op(2, 2)); op = Subtract; Console.WriteLine(op(2, 2)); }
static int[] map(int[] array, IntOperation callback) { int[] result = new int[array.Length]; for (int i = 0; i < array.Length; i++) { result[i] = callback(array[i]); } return(result); }
static public int[] Map(int[] arr, IntOperation op) { int[] res = new int[arr.Length]; for (int i = 0; i < arr.Length; i++) { res[i] = op(arr[i]); } return res; }
public void WhenOperationReturnsValueType_NoGCAllocs() { var op = new IntOperation(); Assert.That(() => { var handle = m_ResourceManager.StartOperation(op, default); handle.Release(); }, TestTools.Constraints.Is.Not.AllocatingGCMemory(), "GC Allocation detected"); }
public void CreateDelegate() { Delegates delegateExpl = new Delegates(); IntOperation addOperation = new IntOperation(delegateExpl.Add); Console.WriteLine(addOperation(5, 5)); IntOperation subtractOperation = new IntOperation(delegateExpl.Substract); Console.WriteLine(subtractOperation(5, 5)); }
public void CustomDelegate() { var op = new IntOperation(Add); var addResult = op(2, 2); Assert.Equal(4, addResult); op = Subtract; Assert.Equal(0, op(2, 2)); }
static void DelegateDemo() { IntOperation operation = Add; operation += Substract; operation += Multiply; operation(10, 10); // foreach (var o in operation.GetInvocationList()) // { // System.Console.WriteLine(o.DynamicInvoke()); // } }
static void Main() { // Инициализируем делегат IntOperation op1 = MyClass.Sum; int result = op1(5, 10); Console.WriteLine("Сумма: " + result); op1 = MyClass.Prz; result = op1(5, 10); Console.WriteLine("Произведение: " + result); Console.ReadLine(); }
static void Main(string[] args) { // Explicitly create the delegate IntOperation op = new IntOperation(Add); Console.WriteLine(op(2, 2)); // Delegate is created automatically // from method op = Subtract; Console.WriteLine(op(2, 2)); }
// It is important to understand the difference between delegate (with a lowercase d) and Delegate (with an upper-case D). The word // delegate with a lower-case d is the keyword used in a C# program that tells the compiler to create a delegate type // The word Delegate with an upper-case D is the abstract class that defines the behavior of delegate instances. // Once the delegate keyword has been used to create a delegate type, objects of that delegate type will be realized as // Delegate instances. /// <summary> /// Lambda expressions /// </summary> // Delegates allow a program to treat behaviors (methods in objects) as items of data. A delegate is an item of data // that serves as a reference to a method in an object. This adds a tremendous amount of flexibility for programmers. // However, delegates are hard work to use. The actual delegate type must first be declared and then made to // refer to a particular method containing the code that describes the action to be performed. Lambda expressions are a // pure way of expressing the “something goes in, something happens and something comes out” part of behaviors. The types // of the elements and the result to be returned are inferred from the context in which the lambda expression is used. // The operator => is called the lambda operator. The items a and b on the left of the lambda expression are mapped onto // method parameters defined by the delegate. The statement on the right of the lambda expression gives the behavior of the expression, // and in this case adds the two parameters together. When describing the behavior of the lambda expression you can use the phrase // “goes into” to describe what is happening. In this case you could say “a and b go into a plus b.” The name // lambda comes from lambda calculus public void LambdaExpressions() { IntOperation add = (a, b) => a + b; add = (a, b) => { Console.WriteLine("Add called"); return(a + b); }; Console.WriteLine(add(2, 2)); }
static void Main(string[] args) { Console.WriteLine("Calling add {0}", add(2, 2)); Console.WriteLine("Calling square {0}", square(2)); add = (a, b) => { Console.WriteLine("Add called"); return(a + b); }; Console.ReadKey(); }
public static void TimerCallback(Object o) { if (a == true) { op = Sum; } else { op = Prz; } Console.WriteLine("Результат: " + op(3, 3)); a = !a; }
public void Run() { // Explicitly create the delegate IntOperation op = new IntOperation(Add); Console.WriteLine(op(2, 2)); // Delegate is created automatically from method op = Subtract; Console.WriteLine(op(2, 2)); Console.ReadKey(); }
public static void TestLamda() { Console.WriteLine("Calling add {0}", add(2, 2)); Console.WriteLine("Calling square {0}", square(2)); add = (a, b) => { Console.WriteLine("Add called"); return(a + b); }; Console.WriteLine("Calling add {0}", add(3, 3)); }
public static void TestMyDelegate() { // A program can use the variable op to either hold a collection of subscribers or to refer to a single method. IntOperation op; // Explicitly create the delegate op = new IntOperation(Add); Console.WriteLine(op(2, 2)); // Delegate is created automatically // from method op = Subtract; Console.WriteLine(op(2, 2)); }
static void Main(string[] args) { var op = new IntOperation(Add); Console.WriteLine(op(2, 2)); op = Substract; Console.WriteLine(op(2, 2)); IntOperation add = (a, b) => a * b; Console.WriteLine(add(2, 2)); Console.ReadKey(); }
static void Main() { // Присваиваем имя метода обычным способом IntOperation op1 = new IntOperation(Sum); // Используем групповое преобразование op1 = Sum; int result = op1(5, 10); Console.WriteLine("Сумма: " + result); // Изменим ссылку на метод op1 = Prz; result = op1(5, 10); Console.WriteLine("Произведение: " + result); Console.ReadLine(); }
static void Main(string[] args) { //Создадим экземпляр делегата IntOperation op1 = new IntOperation(Sum); Console.WriteLine($"Делегат ссылается на метод: {op1.Method}"); int result = op1(5, 10); Console.WriteLine($"Сумма: {result}"); //Изменим ссылку на метод op1 = new IntOperation(Mult); Console.WriteLine($"Делегат ссылается на метод: {op1.Method}"); result = op1(5, 10); Console.WriteLine($"Произведение: {result}"); }
static void Main(string[] args) { Console.WriteLine("Calling add {0}", add(2, 2)); Console.WriteLine("Calling square {0}", square(2)); //CTO: estrutura do lambda é variavel => funcao no qual a variavel é mapeada para a função add = (a, b) => { Console.WriteLine("Add called"); return(a + b); }; add(2, 2); Console.ReadKey(); }
public static void CreateDelegatesExample() { // Explicitly create the delegate var op = new IntOperation((a, b) => { Console.WriteLine("Add called"); return(a + b); }); Console.WriteLine(op(2, 2)); // Delegate is created automatically // from method op = (a, b) => a - b; Console.WriteLine(op(2, 2)); Console.ReadKey(); }
// Up until now we have used the Action and EventHandler types, which provide pre-defined delegates. We can, however, // create our own delegates. Up until now the delegates that we have seen have maintained a collection of method references. // Our applications have used the += and -= operators to add method references to a given delegate. You can also // create a delegate that refers to a single method in an object. A delegate type is declared using the delegate // keyword. public void CreateDelegates() { IntOperation op; // Explicitly create the delegate op = new IntOperation(Add); Console.WriteLine(op(2, 3)); // Delegate is created automatically from method op = Substract; Console.WriteLine(op(2, 3)); // a program can explicitly create an instance of the delegate class. The C# compiler will automatically generate the code // to create a delegate instance when a method is assigned to the delegate variable. Delegates can be used // in exactly the same way as any other variable. You can have lists and dictionaries that contain delegates // and you can also use them as parameters to methods. }
public Operator(Operators op, IntOperation oper = null) { OpType = op; Operation = oper; }
static void Main() { Random rnd = new Random(); IntOperation deleg = new IntOperation(Reduce); int size = 20; int[] massiv = new int[size]; for (int ctr = 1; ctr < size; ctr++) { massiv[ctr] = rnd.Next(1, 99); } Console.WriteLine("Числа рандом"); massiv = Map(massiv, x => x * x); Map(massiv, delegate(int x) { Console.WriteLine(x); return x; } ); Map(massiv, Pow); for (int ctr = 0; ctr < size; ctr++) { int Reduces = deleg(massiv[ctr]); Console.Write("{0} ",massiv[ctr]); } Console.WriteLine("\nУменьшение в 2"); for (int ctr = 0; ctr < size; ctr++) { int Reduces = deleg(massiv[ctr]); Console.Write("{0} ", Reduces); } deleg = new IntOperation(Pow); Console.WriteLine("\nВозводим в квадрат 2"); for (int ctr = 0; ctr < size; ctr++) { int Pows = deleg(massiv[ctr]); Console.Write("{0} ",Pows); } deleg = new IntOperation(Prime); Console.WriteLine("\nПростое число"); for (int ctr = 0; ctr < size; ctr++) { int Primes = deleg(massiv[ctr]); Console.Write("{0} ",Primes); } Console.ReadKey(); }