/// <summary> /// Общий метод для разных потоков на Get запрос с функцией дозированных запросов раз в <paramref name="delay"/> мс и временем ожидания <paramref name="waitingTime"/>, в случае неудачного запроса /// </summary> /// <param name="request">Объект HttpRequest вызывающего потока</param> /// <param name="url">URL строка для Get запроса</param> /// <param name="delay">Время задержки между запросами в мс</param> /// <param name="waitingTime">Время ожидания не ошибочного ответа от сервера</param> /// <param name="setter">делегат передающий сигналу задержки состояние true, означающий недавнее выполнение http get запроса</param> /// <param name="getter">делегат возвращающий текущее состояние сигнала разрешения задержки</param> /// <returns></returns> internal static string GetDosingRequests(HttpRequest request, string url, RequestParams rParams, int delay, int waitingTime, Action<bool> setter, FirstDelegate getter) { string resultPage = ""; Stopwatch waitingWatch = new Stopwatch(); waitingWatch.Start(); while (String.IsNullOrEmpty(resultPage)) { if (getter()) { //этой конструкцией выстраиваю потоки в очередь lock (LockGetRequestObj) { Thread.Sleep(delay); } } try { setter(true); resultPage = request.Get(url, rParams).ToString(); Console.WriteLine("request"); } catch (Exception ex) { if (waitingWatch.ElapsedMilliseconds > waitingTime && waitingTime != -1) throw new Exception("Время ожидания вышло. Причина: \r\n" + ex.Message); Thread.Sleep(5000); } } waitingWatch.Reset(); return resultPage; }
/* Пример программы содержащей один статический и один экземплярный методы. Вызов DelegateTest.StaticMethod эквивалентен вызову StaticMethod */ public static void Test() { FirstDelegate d1 = new FirstDelegate(DelegateTest.StaticMethod); DelegateTest instance = new DelegateTest(); instance.name = "My instance"; FirstDelegate d2 = new FirstDelegate(instance.InstanceMethod); Console.WriteLine($"Delegate 1 {d1(10)} with target: {d1.Target}");// shows Static method 10 Console.WriteLine($"Delegate 2 {d2(5)} with target: {d2.Target}");// shows My instance: 5 }
static int[] map(int[] array, FirstDelegate userDelegate) { int[] result = new int[array.Length]; for (int i = 0; i < array.Length; ++i ) { result[i] = userDelegate(array[i]); } return result; }
static void Main(string[] args) { //Initialization FirstDelegate f1 = new FirstDelegate(Method1); FirstDelegate f2 = new FirstDelegate(Method2); FirstDelegate f3 = new FirstDelegate(Method3); //Invocation f1(); f2(); f3(); Console.Read(); }
public static void Main() { // Using the old .Net 1/1.1 syntax FirstDelegate d1 = new FirstDelegate(Program.StaticMethod); Program instance = new Program("Created my instance"); instance.name = "My instance"; FirstDelegate d2 = new FirstDelegate(instance.InstanceMethod); Console.WriteLine(d1(10)); // Writes out "Static method: 10" Console.WriteLine(d2(5)); // Writes out "My instance: 5" // Using new simplified syntax FirstDelegate n1 = StaticMethod; FirstDelegate n2 = (new Program("Instance new way")).InstanceMethod; Console.WriteLine(n1.Invoke(88)); Console.WriteLine(n2.Invoke(22)); Console.WriteLine(n1(101)); // Writes out "Static method: 10" Console.WriteLine(n2(102)); // Writes out "My instance: 5" Dictionary <string, string> dc1 = new Dictionary <string, string>(); dc1.Add("Yuriy", "Gruzglin"); dc1.Add("Anna", "Montana"); dc1.Add("Joy", "Bennet"); dc1["Stella"] = "Artoit"; dc1.Append(new KeyValuePair <string, string>("Gerald", "Ford")); dc1.Append(new KeyValuePair <string, string>("Ray", "Holmes")); foreach (KeyValuePair <string, string> z in dc1) { Console.WriteLine(z.Key + " " + z.Value); } string y; if (dc1.TryGetValue("Joy", out y)) { Console.WriteLine("Joy " + y); } Console.ReadLine(); }
static void Main(string[] args) { int n = 77777; int[] arr = { 10, 20, 30, 40, 50, 60, 70, 77, 80, 90, }; FirstDelegate firs = new FirstDelegate(FormMass); SecondDelegate second = new SecondDelegate(PrintMass); PrintMass(FormMass(n)); Console.WriteLine(); PrintMass(arr); Console.WriteLine(); Console.WriteLine($"{firs.Method}\t{firs.Target}"); Console.WriteLine($"{second.Method}\t{second.Target}"); }
public (FirstDelegate, FirstDelegate) DelegateInstanceCreationDemo(ClassWithTheStaticAndInstanceMethod theOtherClassInstance) { // 1. FirstDelegate instance created by passing an instance methos if "this" class. FirstDelegate d1 = new FirstDelegate(this.OwnInstanceMethod); // 2. FirstDelegate instance created by passing the other class instance method. // "TheOtherClassInstanceMethod" must be visible at the moment of creation, so it is public. FirstDelegate d2 = new FirstDelegate(theOtherClassInstance.TheOtherClassInstanceMethod); // 3. FirstDelegateInstance created by passing this class static method. FirstDelegate d3 = new FirstDelegate(StaticMethod); // 4. FirstDelegate instance created by passing the other class static method. // "StaticMethod" must be visible at the moment of creation hence it is public in ClassWithTheStaticAndInstanceMethod. FirstDelegate d4 = new FirstDelegate(ClassWithTheStaticAndInstanceMethod.TheOtherClassStaticMethod); return(d1, d3); }
static void Main(string[] args) { FirstDelegate d1 = new FirstDelegate(StaticMethod); DelegateTest instance = new DelegateTest(); instance.name = "My instance"; FirstDelegate d2 = new FirstDelegate(instance.InstanceMethod); Console.WriteLine(d1(10)); // Writes out "Static method: 10" Console.WriteLine(d2(5)); // Writes out "My instance: 5" }
static void Main(string[] args) { #region //DotNET 1.0 FirstDelegate first = new FirstDelegate(Square); Console.WriteLine(first(3)); //4.0 SecondDelegate second = Print; second += Display; Execute(second); //second.Invoke(); #endregion /* * Anonymous method */ //2 FirstDelegate df = delegate(int a) { return(a * a); }; Console.WriteLine(df(6)); //3.5 df = (a => a * a * a); Console.WriteLine(df(3)); Console.WriteLine(func("duong", 20)); //Func<int, int, int> f = ((a, b) => { // return a + b; //}); //Console.WriteLine(f(7,3)); Run(func, "phat", 100); Console.ReadLine(); }
public static void UseDelegateWithDifferentMethods(FirstDelegate firstDelegate) { string input = Console.ReadLine(); firstDelegate(input); }
public AttackAnimation(string name, int duration, TriggerDelegate trigger = null, FirstDelegate first = null, TickDelegate tick = null, FinalDelegate final = null) : base(name, duration, trigger, first, tick, final) { }
/// <summary> /// Общий метод для разных потоков на Get запрос с функцией дозированных запросов раз в <paramref name="delay"/> мс и временем ожидания <paramref name="waitingTime"/>, в случае неудачного запроса /// </summary> /// <param name="request">Объект HttpRequest вызывающего потока</param> /// <param name="url">URL строка для Get запроса</param> /// <param name="delay">Время задержки между запросами в мс</param> /// <param name="waitingTime">Время ожидания не ошибочного ответа от сервера</param> /// <param name="setter">делегат передающий сигналу задержки состояние true, означающий недавнее выполнение http get запроса</param> /// <param name="getter">делегат возвращающий текущее состояние сигнала разрешения задержки</param> /// <returns></returns> internal static string GetDosingRequests(HttpRequest request, string url, RequestParams rParams, int delay, int waitingTime, Action <bool> setter, FirstDelegate getter) { string resultPage = ""; Stopwatch waitingWatch = new Stopwatch(); waitingWatch.Start(); while (String.IsNullOrEmpty(resultPage)) { if (getter()) { //этой конструкцией выстраиваю потоки в очередь lock (LockGetRequestObj) { Thread.Sleep(delay); } } try { setter(true); resultPage = request.Get(url, rParams).ToString(); Console.WriteLine("request"); } catch (Exception ex) { if (waitingWatch.ElapsedMilliseconds > waitingTime && waitingTime != -1) { throw new Exception("Время ожидания вышло. Причина: \r\n" + ex.Message); } Thread.Sleep(5000); } } waitingWatch.Reset(); return(resultPage); }