public static void Main() { MyDelegate a, b, c, d; // Create the delegate object a that references // the method Hello: a = new MyDelegate(Hello); // Ex A1 - Atribuição de Métodos // Create the delegate object b that references // the method Goodbye: b = new MyDelegate(Goodbye); // Ex A1 - Atribuição de Métodos // The two delegates, a and b, are composed to form c: c = a + b; // Ex A1 - Adição de Métodos // Remove a from the composed delegate, leaving d, // which calls only the method Goodbye: d = c - a; // Ex A1 - Subtração de métodos Console.WriteLine("Invoking delegate a:"); a("A"); // Ex A1 - Invocação Console.WriteLine("Invoking delegate b:"); b("B"); // Ex A1 - Invocação Console.WriteLine("Invoking delegate c:"); c("C"); // Ex A1 - Invocação // Ex A2 - Não é garantida a ordem de invocação Console.WriteLine("Invoking delegate d:"); d("D"); // Ex A1 - Invocação // Ex A2 - Não é garantida a ordem de invocação // Ex A6 Console.WriteLine("Invoking method delegate:"); callDelegate(a); Console.Read(); }
private void btn_asyncTest_Click(object sender, EventArgs e) { //Assign a function to the delegate myAsync = new MyDelegate(this.SomeFunction); myAsync.BeginInvoke(5, 10, null, null); }
static void Main(string[] args) { MyDelegate arithmethod = null; Console.WriteLine("Please insert two integer numbers"); int input1 = Convert.ToInt32(Console.ReadLine()); int input2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Please choose your operation as + , - , * , M"); char operationinput = Convert.ToChar(Console.ReadLine()); switch (operationinput) { case '+': arithmethod = new MyDelegate(Add); break; case '-': arithmethod = new MyDelegate(Subtrac); break; case '*': arithmethod = new MyDelegate(Multiply); break; case 'M': arithmethod = new MyDelegate(Max); break; } int r = arithmethod(input1, input2); Console.WriteLine("The result of your {0} operation is {1}", operationinput, r); Console.ReadLine(); }
public DelegateTimer(DelegateTimerKey key, MyDelegate d, float remainTime) { mTimerKey = key; mDelegate = d; mTime = remainTime; mRemainTime = remainTime; }
public MFTestResults SystemReflectionType_ObjectGetType_Test0() { bool fRes = true; /// /// Test object.GetType method for various types (including /// reflection types and arrays of reflection types). /// object o = (object)1; fRes &= (o.GetType() == typeof(int)); o = (object)typeof(Type); fRes &= o.GetType() == typeof(Type).GetType(); o = AppDomain.CurrentDomain.GetAssemblies(); fRes &= o.GetType() == typeof(Assembly[]); o = new TestClass(); fRes &= o.GetType() == typeof(TestClass); o = new TestStruct(); fRes &= o.GetType() == typeof(TestStruct); o = new MyDelegate(MyDelegateImpl); fRes &= o.GetType() == typeof(MyDelegate); o = (new MyDelegate(MyDelegateImpl)).Method; Debug.Print("object (MethodInfo) GetType: " + o.GetType().ToString()); MethodInfo mi = typeof(SystemReflectionTypeTests).GetMethod("MyDelegateImpl", BindingFlags.Static | BindingFlags.NonPublic); fRes &= o.GetType() == mi.GetType(); return fRes ? MFTestResults.Pass : MFTestResults.Fail; }
public static void Main() { MyDelegate a, b, c, d; // Create the delegate object a that references // the method Hello: a = new MyDelegate(Hello); // Create the delegate object b that references // the method Goodbye: b = new MyDelegate(Goodbye); // The two delegates, a and b, are composed to form c: c = a + b; // Remove a from the composed delegate, leaving d, // which calls only the method Goodbye: d = c - a; Console.WriteLine("Invoking delegate a:"); a("A"); Console.WriteLine("Invoking delegate b:"); b("B"); Console.WriteLine("Invoking delegate c:"); c("C"); Console.WriteLine("Invoking delegate d:"); d("D"); }
public void TestCombineRemove() { MyDelegate dela = new MyDelegate( MethodA ); MyDelegate delb = new MyDelegate( MethodB ); MyDelegate delc = new MyDelegate( MethodC ); MyDelegate deld = new MyDelegate( MethodD ); string val; char res; // test combine MyDelegate del1, del2; del1 = dela + delb + delb + delc + delb + delb + deld; val = ""; res = del1( ref val ); Assert.AreEqual("abbcbbd", val , "#A01"); Assert.AreEqual('d', res , "#A02"); // test remove del2 = del1 - ( delb + delb ); val = ""; res = del2( ref val ); Assert.AreEqual("abbcd", val , "#A03"); Assert.AreEqual('d', res , "#A04"); // we did not affect del1, did we? val = ""; res = del1( ref val ); Assert.AreEqual("abbcbbd", val , "#A05"); }
public void Forget(string eventName, MyDelegate subscriber) { if (events.Keys.Contains(eventName)) { events[eventName] -= subscriber; } }
public static void Main() { MyDelegate a, b, c, d; // 创建引用 Hello 方法的 // 委托对象 a: a = new MyDelegate(Hello); // 创建引用 Goodbye 方法的 // 委托对象 b: b = new MyDelegate(Goodbye); // a 和 b 两个委托组成 c, // c 将按顺序调用这两个方法: c = a + b; // 从组合委托中移除 a 而保留 d, // 后者仅调用 Goodbye 方法: d = c - a; Console.WriteLine("Invoking delegate a:"); a("A"); Console.WriteLine("Invoking delegate b:"); b("B"); Console.WriteLine("Invoking delegate c:"); c("C"); Console.WriteLine("Invoking delegate d:"); d("D"); }
static void Main(string[] args) { MyClass obj = new MyClass(); MyDelegate del1 = new MyDelegate(obj.Func1); del1 += new MyDelegate(obj.Func2); //上面两句可以简写为以下形式: //MyDelegate del1 = obj.Func1; //del1 += obj.Func2; Delegate[] ds; ds = del1.GetInvocationList(); Console.WriteLine("del1的委托调用列表中包含{0}个方法", ds.GetLength(0)); del1(5); //先调用obj1.Func1(),再调用obj1.Func2() MyDelegate del2 = new MyDelegate(obj.Func1); del2 += new MyDelegate(obj.Func2); //组合委托 Delegate mul = del1 + del2; ds = mul.GetInvocationList(); Console.WriteLine("mul的委托调用列表中包含{0}个方法", ds.GetLength(0)); int ret = (mul as MyDelegate)(10); //获取委托调用列表最后一个方法的返回值 Console.WriteLine("ret = {0}", ret); Console.ReadKey(); }
public static void Main(){ MyDelegate call = new MyDelegate(FirstMethod); call += new MyDelegate(SecondMethod); call("Message A"); call("Message B"); call("Message C"); }
public void Run() { MyStruct s = new MyStruct(); s.b = "OK"; MyDelegate dg = new MyDelegate(s.Test); dg(); }
public DelegateTimer(DelegateTimerKey key, MyDelegate d, float remainTime, bool looping) { mTimerKey = key; mDelegate = d; mRemainTime = remainTime; mTime = remainTime; isLooping = looping; }
public static void button2_Click(object sender, EventArgs e) { // Opret derefter en ny knap, der ved tryk starter en ny tråd. Den nye tråd skal have // angivet en startmetode. Fra denne startmetode kaldes den metode, der udskriver noget // i tekstboksen med det, man ønsker udskrevet, som parameter. MyDelegate del = new MyDelegate(button1_Click); del("Hello from delegate"); }
delegate string MyDelegate();//声明委托 static void Main(string[] args) { Helloworld hello = new Helloworld(); MyDelegate h = new MyDelegate(hello.HelloCN); Console.WriteLine(h()); h = new MyDelegate(hello.HelloEN); Console.WriteLine(h()); }
void Start() { myDelegate = PrintNum; // assign the delegate to the method myDelegate(50); // use the delegate myDelegate = DoubleNum; // re-assign the delegate to the other method myDelegate(50); // re-use the delegate }
static void Main(string[] args) { deli = new MyDelegate(MyMethod); Console.WriteLine("Invoking the method..."); result = deli.BeginInvoke(MyMethodEnds, null); Console.WriteLine("Reached Console.ReadKey()"); Console.ReadKey(); }
public void Subscribe(string eventName, MyDelegate subscriber) { if (!events.Keys.Contains(eventName)) { events.Add(eventName, null); } events[eventName] += subscriber; }
public MyDelegate neuDelegate() { Class1 c2 = new Class1(); MyDelegate d1 = new MyDelegate(c2.delegateMethod1); MyDelegate d2 = new MyDelegate(c2.delegateMethod2); MyDelegate d3 = d1 + d2; return d3; }
public void idleAnimation() { // Color the spider during idle. GetComponent<SpriteRenderer>().color = Color.green; Debug.Log("Idling"); velocity = 0; targetPlayer = false; enemyAction = TargetInZone; }
void Start() { myDelgate = Test; myDelgate(); myDelgate += Test2; myDelgate(); myDelgate = Test3; myDelgate(); }
static void Main(string[] args) { // Create inst of the delegate. var myDel = new MyDelegate<string> (Simple.PrintString); // Add a method. myDel += Simple.PrintUpperString; // Call the delegate. myDel("Hello, Jack!"); }
public static MyDelegate [] getDelegates() { MyDelegate [] del = new MyDelegate[3]; for(int i =0; i < 3; i++) { del[i] = delegate{Console.WriteLine("Hi");}; } return del; }
static void Main(string[] args) { MyDelegate objMyDelegate = new MyDelegate(Addition); objMyDelegate += Substruction; objMyDelegate += Divition; objMyDelegate += Multiplication; objMyDelegate -= Divition; objMyDelegate(10,5); Console.Read(); }
private void friendsNear() { if (isFriendClose()) { Debug.Log("Friends Near True"); enemyAction = attack; } else { Debug.Log("Friends Near False"); enemyAction = hpLow; } }
/* Action Functions -----------------------------------------------*/ private void attack() { this.gameObject.GetComponent<SpriteRenderer>().color = originalColor; // code to target player Debug.Log("Attacking"); runFromPlayer = false; targetPlayer = true; velocity = speed; enemyAction = TargetInZone; }
public EyeState(Arduino i_Arduino) { initOperationsDictionary(); m_Arduino = i_Arduino; Closed += eyeState_Closed; Open += eyeState_Open; m_StopwatchBuffer = new Stopwatch(); }
public MainWindow() { InitializeComponent(); userDispatcher = Dispatcher.CurrentDispatcher; del = new MyDelegate(this.DisplayLog); _mediaConsumer = new TCPClient(); _mediaProducer = new TCPClient(); Log.Register(this); }
static void Main3() { MyDelegate d1 = new MyDelegate(f1); MyMath m1 = new MyMath(); MyMathDelegate d2 = new MyMathDelegate(m1.Addition); d2 += m1.Subtraction; d2 += m1.Multiplication; //Multicast delegate Test(d1, d2); }
public void TestMethod1() { MyDelegate d = new MyDelegate(Convert); int result = d.Invoke("1"); Assert.AreEqual(1, result); d("2"); // Verkorte schrijfwijze voor initializatie MyDelegate d2 = Convert; }
private async Task AssignmentDefaults() { using (var uow = new UnitOfWork(Tsdl)) { if (!uow.Query <AssignmentType>().Any(x => x.TypeName == UNK)) { var at = new AssignmentType(uow) { TypeName = UNK, TypeDescription = UNK }; uow.CommitChanges(); } } using (var odw = new OracleDatabaseWorker(tbOracleConnectionStringText)) { //just good olfd status for now List <string> statuses = odw.GetDistinctDataColumn(assignmentPrimlocTable, "STATUS"); List <string> Classes = odw.GetDistinctDataColumn(assignmentPrimlocTable, "ASSIGNMENTCLASS"); statuses.Add(GlobalSystemSettings.AssignmentStatusActive); //class var del = new MyDelegate((lst) => { using (var uow = new UnitOfWork(Tsdl)) { foreach (var str in lst.Where(s => s != "" && !uow.Query <AssignmentStatus>().Select(x => x.StatusName).Contains(s))) { AssignmentStatus cs = new AssignmentStatus(uow) { StatusName = str }; uow.CommitChanges(); } } return(true); }); IAsyncResult sres = del.BeginInvoke(statuses, null, null); del = new MyDelegate((lst) => { using (var uow = new UnitOfWork(Tsdl)) { foreach (var str in lst.Where(s => s != "" && !uow.Query <AssignmentClass>().Select(x => x.Class).Contains(s))) { AssignmentClass cs = new AssignmentClass(uow) { Class = str }; uow.CommitChanges(); } } return(true); }); IAsyncResult cres = del.BeginInvoke(Classes, null, null); await Task.FromResult(sres); await Task.FromResult(cres); } }
static void Main(string[] args) { MyDelegate Add = delegate(int x, int y) { return(x + y); }; MyDelegate Sub = (int x, int y) => { return(x - y); }; MyDelegate Mul = (x, y) => x * y; MyDelegate Div = (int x, int y) => { if (y == 0) { Console.WriteLine("Деление на ноль!"); return(0); } return(x / y); }; int a, b; Console.WriteLine("Введите два числа: "); try { a = Int32.Parse(Console.ReadLine()); b = Int32.Parse(Console.ReadLine()); } catch (Exception) { a = 1; b = 1; Console.WriteLine("Ошибка ввода"); } Console.WriteLine("Сложение {0}", Add.Invoke(a, b)); Console.WriteLine("Вычитание {0}", Sub.Invoke(a, b)); Console.WriteLine("Умножение {0}", Mul(a, b)); Console.WriteLine("Деление {0}", Div(a, b)); // //Второй способ Console.WriteLine(new string('-', 30)); Console.WriteLine("Введите оператор +,-,*,/"); string op = Convert.ToString(Console.ReadLine()); MyDelegate multi = null; switch (op) { case "+": multi = (x, y) => x + y; break; case "-": multi = (x, y) => x - y; break; case "*": multi = (x, y) => x * y; break; case "/": multi = (x, y) => { if (y == 0) { Console.WriteLine("Деление на ноль!"); return(0); } return(x / y); }; break; default: Console.WriteLine("Неправильно введен знак операции!"); break; } if (multi != null) { Console.WriteLine("{0:##.###}", multi(a, b)); } Console.ReadKey(); }
static void Main(string[] args) { MyDelegate myDelegate = new MyDelegate(MyClass.Method); myDelegate(); }
public void Remove(MyDelegate f) { _functions -= f; }
public string MyMethod(string label, MyDelegate myDelegate) { return($"{label} : {myDelegate("1", "park")}"); }
public void Function(MyDelegate func) { func(1, 2); }
public void Method3() { MyDelegate myDelegate = new MyDelegate(Method1); myDelegate(); }
public void Process(MyDelegate myDelegate) { }
public static void TakesADelegate(MyDelegate SomeFunction) { //컴파일 시점에 할일이 지정되지 않고 런타임중에 //메소드 인자로 대입되는 델리게이트에 의해 할 일이 결정된다 Console.WriteLine(SomeFunction(1, 2)); }
public SimpleEventClass() { SimpleEvent += new MyDelegate(PrintText); }
public Timer(MyDelegate method, int interval, int times) : this(method, interval) { this.times = times; }
static void InvokeDelegate(MyDelegate del) { del("Hello World"); }
static void Sum(int x, MyDelegate dl) { int a = dl(7); Console.WriteLine(a); }
public void M() { // Static field, tainted Test.SinkField0 = "taint source"; Check(Test.SinkField0); // Static field, not tainted Test.NonSinkField0 = "not tainted"; Check(Test.NonSinkField0); // Static property, tainted Test.SinkProperty0 = Test.SinkField0; Check(Test.SinkProperty0); // Static property, not tainted Test.NonSinkProperty0 = Test.NonSinkField0; Check(Test.NonSinkProperty0); Test.NonSinkProperty1 = Test.SinkField0; Check(Test.NonSinkProperty1); // Flow into a callable (non-delegate), tainted In0(Test.SinkProperty0); var methodInfo = typeof(DataFlow).GetMethod("In1"); var args = new object[] { Test.SinkProperty0 }; methodInfo.Invoke(null, args); // Flow into a callable (non-delegate), not tainted NonIn0(""); // Flow into a callable (delegate, locally resolvable), tainted Action <string> in2 = sinkParam2 => Check(sinkParam2); in2(Test.SinkProperty0); // Flow into a callable (delegate, locally resolvable), not tainted Action <string> nonIn1 = nonSinkParam1 => Check(nonSinkParam1); nonIn1(""); // Flow into a callable (delegate, resolvable via call), tainted Apply(In3, Test.SinkProperty0); Apply(x => In4(x), Test.SinkProperty0); ApplyDelegate(new MyDelegate(In5), Test.SinkProperty0); ApplyDelegate(In6, Test.SinkProperty0); myDelegate = new MyDelegate(x => In7(x)); ApplyDelegate(myDelegate, Test.SinkProperty0); // Flow into a callable (delegate, resolvable via call), not tainted Apply(nonSinkParam0 => Check(nonSinkParam0), "not tainted"); ApplyDelegate(new MyDelegate(nonSinkParam0 => Check(nonSinkParam0)), "not tainted"); // Flow into a callable (property), tainted InProperty = Test.SinkProperty0; // Flow into a callable (property), not tainted NonInProperty = "not tainted"; // Flow through a callable that returns the argument (non-delegate), tainted var sink0 = Return(Test.SinkProperty0); Check(sink0); var sink1 = (string)typeof(DataFlow).GetMethod("Return").Invoke(null, new object[] { sink0 }); Check(sink1); string sink2; ReturnOut(sink1, out sink2, out var _); Check(sink2); var sink3 = ""; ReturnRef(sink2, ref sink3, ref sink3); Check(sink3); var sink13 = ((IEnumerable <string>) new string[] { sink3 }).SelectEven(x => x).First(); Check(sink13); var sink14 = ((IEnumerable <string>) new string[] { sink13 }).Select(ReturnCheck).First(); Check(sink14); var sink15 = ((IEnumerable <string>) new string[] { sink14 }).Zip(((IEnumerable <string>) new string[] { "" }), (x, y) => x).First(); Check(sink15); var sink16 = ((IEnumerable <string>) new string[] { "" }).Zip(((IEnumerable <string>) new string[] { sink15 }), (x, y) => y).First(); Check(sink16); var sink17 = ((IEnumerable <string>) new string[] { sink14 }).Aggregate("", (acc, s) => acc + s, x => x); Check(sink17); var sink18 = ((IEnumerable <string>) new string[] { "" }).Aggregate(sink14, (acc, s) => acc + s, x => x); Check(sink18); int sink21; Int32.TryParse(sink18, out sink21); Check(sink21); bool sink22; bool.TryParse(sink18, out sink22); Check(sink22); // Flow through a callable that returns the argument (non-delegate), not tainted var nonSink0 = Return(""); Check(nonSink0); nonSink0 = (string)typeof(DataFlow).GetMethod("Return").Invoke(null, new object[] { nonSink0 }); Check(nonSink0); ReturnOut("", out nonSink0, out string _); Check(nonSink0); ReturnOut(sink1, out var _, out nonSink0); Check(nonSink0); ReturnRef("", ref nonSink0, ref nonSink0); Check(nonSink0); ReturnRef(sink1, ref sink1, ref nonSink0); Check(nonSink0); nonSink0 = ((IEnumerable <string>) new string[] { nonSink0 }).SelectEven(x => x).First(); Check(nonSink0); nonSink0 = ((IEnumerable <string>) new string[] { nonSink0 }).Select(x => x).First(); Check(nonSink0); nonSink0 = ((IEnumerable <string>) new string[] { sink14 }).Zip(((IEnumerable <string>) new string[] { "" }), (x, y) => y).First(); Check(nonSink0); nonSink0 = ((IEnumerable <string>) new string[] { "" }).Zip(((IEnumerable <string>) new string[] { sink15 }), (x, y) => x).First(); Check(nonSink0); nonSink0 = ((IEnumerable <string>) new string[] { sink14 }).Aggregate("", (acc, s) => acc, x => x); Check(nonSink0); nonSink0 = ((IEnumerable <string>) new string[] { sink14 }).Aggregate("", (acc, s) => acc + s, x => ""); Check(nonSink0); nonSink0 = ((IEnumerable <string>) new string[] { nonSink0 }).Aggregate(sink1, (acc, s) => s, x => x); Check(nonSink0); int nonSink2; Int32.TryParse(nonSink0, out nonSink2); Check(nonSink2); bool nonSink3; bool.TryParse(nonSink0, out nonSink3); Check(nonSink3); // Flow through a callable that returns the argument (delegate, locally resolvable), tainted Func <string, string> @return = x => ApplyFunc(Return, x); var sink4 = @return(sink3); Check(sink4); // Flow through a callable that returns the argument (delegate, locally resolvable), not tainted nonSink0 = @return(nonSink0); Check(nonSink0); // Flow through a callable that returns the argument (delegate, resolvable via call), tainted var sink5 = ApplyFunc(Return, sink4); Check(sink5); // Flow through a callable that (doesn't) return(s) the argument (delegate, resolvable via call), not tainted nonSink0 = ApplyFunc(Return, ""); Check(nonSink0); nonSink0 = ApplyFunc(_ => "", sink5); Check(nonSink0); // Flow out of a callable (non-delegate), tainted var sink6 = Out(); Check(sink6); string sink7; OutOut(out sink7); Check(sink7); var sink8 = ""; OutRef(ref sink8); Check(sink8); var sink12 = OutYield().First(); Check(sink12); var sink23 = TaintedParam(nonSink0); // even though the argument is not tainted, the parameter is considered tainted Check(sink23); // Flow out of a callable (non-delegate), not tainted nonSink0 = NonOut(); Check(nonSink0); NonOutOut(out nonSink0); Check(nonSink0); NonOutRef(ref nonSink0); Check(nonSink0); nonSink0 = NonOutYield().First(); Check(nonSink0); nonSink0 = NonTaintedParam(nonSink0); Check(nonSink0); // Flow out of a callable (delegate), tainted Func <string> @out = () => "taint source"; var sink9 = @out(); Check(sink9); // Flow out of a callable (delegate), not tainted Func <string> nonOut = () => ""; nonSink0 = nonOut(); Check(nonSink0); // Flow out of a callable (method access), tainted var sink10 = new Lazy <string>(Out).Value; Check(sink10); // Flow out of a callable (method access), not tainted nonSink0 = new Lazy <string>(NonOut).Value; Check(nonSink0); // Flow out of a callable (property), tainted var sink19 = OutProperty; Check(sink19); // Flow out of a callable (property), not tainted nonSink0 = NonOutProperty; Check(nonSink0); }
public void F() { MyDelegate del = delegate { Console.WriteLine("hello!"); }; }
public DelegateUsageFromDictionary(MyDelegate myDelegate, double dParam1, double dParam2) { this.myDelegate = myDelegate; this.dParam1 = dParam1; this.dParam2 = dParam2; }
static void myMethodCallBack(int param1, int param2, MyDelegate callBack) { callBack("number is :" + (param1 + param2).ToString()); }
static void Main(string[] args) { bool continuar = true; do { switch (Menu()) { case 1: Console.WriteLine("*******************************"); Console.WriteLine("Sistema de registro de clientes"); Console.WriteLine("*******************************"); CuentaBancaria cuenta = new CuentaBancaria(); Console.Write("Ingrese el nombre del cliente: "); cuenta.nombrePropietario = Console.ReadLine(); Console.Write("Ingrese el saldo: "); cuenta.saldoActual = Convert.ToDouble(Console.ReadLine()); lista.Add(cuenta); Console.WriteLine(); break; case 2: Cuentas(); break; case 3: md = new MyDelegate(Cuentas); md += new MyDelegate(TotalCuentas); md(); break; case 4: Action MyAction; MyAction = () => { Console.WriteLine("*******************************"); Console.WriteLine(" Cuentas almacenadas"); Console.WriteLine("*******************************"); foreach (var element in lista) { Console.WriteLine("Nombre: " + element.nombrePropietario); Console.WriteLine("Saldo actual: " + element.saldoActual); Console.WriteLine(); } }; MyAction += () => { double suma = 0; Console.WriteLine("********************"); Console.WriteLine("Total de las cuentas"); Console.WriteLine("********************"); foreach (var element in lista) { suma += element.saldoActual; } Console.WriteLine("$" + suma); Console.WriteLine(); }; MyAction += CuentasVocal; MyAction(); break; case 5: continuar = false; break; } } while (continuar); }
public void PrintMessage(MyDelegate d) { d(); }
public static double OddNumber(double number, MyDelegate @delegate) { return(@delegate(number)); }
public void Add(MyDelegate f) { _functions += f; }
void Method3() { System.Console.WriteLine(MyDelegate.ToString()); }
static void Main(string[] args) { //f(x) = x + 1 MyDelegate md1 = x => x + 1; Console.WriteLine(md1(2)); //f(x) = x^2 + 2*x + 4 md1 = x => x * x + 2 * x + 4; Console.WriteLine(md1(2)); //Вычислить корень квадратный md1 = y => Math.Sqrt(y); Console.WriteLine(md1(25)); //s = 1/2 + 1/3 + ... 1/n md1 = z => { double s = 0; for (int i = 2; i <= z; i++) { s += 1.0 / 1; } return(s); }; Console.WriteLine(md1(10)); //Как получить сумму квадратов чисел MathDelegate md; //Использование анонимного метода. Представление анонимного метода через делегат //Передаем делегату блок кода, который и является анонимным методом md = delegate(int x, int y) { return((x * x) + (y * y)); }; Console.WriteLine("5*5 + 3*3 = {0}", md(5, 3)); //Использование лямбда выражения вместо анонимного метода. Представления через лямбда выражение md = (x, y) => (x * x) + (y * y); Console.WriteLine("5*5 + 3*3 = {0}", md(5, 3)); //Лямбда выражение представляет собой упрощенную запись анонимных методов //------------------------------------------------------------------------- //Стандарный делегат Action<> //Инкапсулирует метод, который принимает от 1 до 16 параметров //и не возвращает значение //используется для методов которые ничего не возвращают Action <string> PrintString; PrintString = s => Console.WriteLine(s); PrintString("Hello World!"); Action <int, int> PrintSumm; PrintSumm = (x, y) => Console.WriteLine(x + y); PrintSumm(2, 3); //--------------------------------------------------------------------------- //Func<T, TResult> - стандартный делегат //Инкапсулирует метод с одним параметром и возвращает значение типа, указанного в параметре TResult. Func <int, double> f1 = x => x / 2; Func <double, double> f2 = x => x / 2; Func <double, int> f3 = x => (int)x / 2; int n = 9; Console.WriteLine("Result 1 = {0}", f1(n)); Console.WriteLine("Result 2 = {0}", f2(n)); Console.WriteLine("Result 3 = {0}", f3(n)); Func <int, int, bool> f = (x, y) => x == y; int a = 5, b = 6, c = 5; if (f(a, c)) { Console.WriteLine("Числа равны"); } else { Console.WriteLine("Числа не равны"); } //---------------------------------------------------------------------------- //Реалтзация функции определяющая максимум из трех значений Func <int, int, int, int> max3 = (k, l, m) => Math.Max(Math.Max(k, l), m); Console.WriteLine(max3(2, 8, 5)); //---------------------------------------------------------------------------- //------------------------------------------------------------ var teamMembers = new List <string> { "Lou Loomis", "Smoke Porterhouse", "Danny Smith", "Ty Webb", "Crocodail Danny", "Dannyil Jobs" }; Console.WriteLine("\nВсе строки, содержащие Danny"); FindByName(teamMembers, "Danny", (x, y) => x.Contains(y)); Console.WriteLine("\nВсе строки, длиннее Danny"); FindByName(teamMembers, "Danny", (x, y) => x.Length > y.Length); Console.WriteLine("\nВсе строки, начинающиеся так же как и Danny"); FindByName(teamMembers, "Danny", (x, y) => x[0] == y[0]); //Расширяющий метод для колл и массив который будет получать в качестве параметра предикат //Прообраз LINQ.. int[] lst = { 3, -6, 2, -7, 8, 5, 4 }; Console.WriteLine(); var data1 = lst.FindItems(x => x % 2 == 0); foreach (var t in data1) { Console.WriteLine(t); } Console.WriteLine(); var data2 = lst.FindItems(x => x % 2 != 0); foreach (var t in data2) { Console.WriteLine(t); } Console.WriteLine(); var data3 = lst.FindItems(x => x > 0); foreach (var t in data3) { Console.WriteLine(t); } Console.ReadKey(); }
//使用MyDelegate类型变量作为方法参数 static void PerformArithoperation(int a, int b, MyDelegate arithOperation) { int r = arithOperation(a, b); Console.WriteLine("\n对3和4执行算数操作后的结果是:{0}", r); }
static void Main() { MyDelegate myDelegate = null; /// помним, что null - значение по умолчанию для всех ссылочных типов; MyDelegate myDelegate1 = new MyDelegate(Method1); /// сообщаем экземпляр делегата MyDelegate с методом Method1; MyDelegate myDelegate2 = new MyDelegate(Method2); MyDelegate myDelegate3 = new MyDelegate(Method3); // Комбинируем делегаты. myDelegate = myDelegate1 + myDelegate2 + myDelegate3; /// Здесь, при работе с делегатами оператор "+" - это знак комбинации или знак группировки. /// 49:17 - описание низкоуровневого подхода с графиком от ведущего по формированию группового делегата; /// Якобы на собеседовании может быть вопрос описать процесс создания комбинированного делегата. /// myDelegate1 + myDelegate2 дают промежуточный делегат по слабой ссылке, который уничтожается сборщиком мусора. /// 52:16 - в итоге получили новый экземпляр делегата (уже по сильной ссылке), который содержит в себе 3 указателя на 3 разных метода. /// Мы получили чемодан, куда вложены 3 метода, стараемся не использовать слово "указатель". Указатель - адрес метода в памяти. /// Создали комбинацию из 3-х делегатов. Console.WriteLine("Введите число от 1 до 7"); string choice = Console.ReadLine(); /// принимаем ввод от пользователя и помещаем его в переменную choice; switch (choice) /// создаем переключатель switch и в качестве выражения селектора передаем значение, введенное пользователем; { case "1": { myDelegate1.Invoke(); break; } case "2": { myDelegate2.Invoke(); break; } case "3": { myDelegate3.Invoke(); break; } case "4": { MyDelegate myDelegate4 = myDelegate - myDelegate1; /// "-" знак разгруппировки myDelegate4.Invoke(); break; } case "5": { MyDelegate myDelegate5 = myDelegate - myDelegate2; /// открепляем второй метод; при этом переменная myDelegate не изменяется (immutable). myDelegate5.Invoke(); break; } case "6": { MyDelegate myDelegate6 = myDelegate - myDelegate3; myDelegate6.Invoke(); break; } case "7": { myDelegate.Invoke(); break; } default: { Console.WriteLine("Вы ввели недопустимое значение."); break; } } // Delay. Console.ReadKey(); }
public void delegateCombine(MyDelegate fun) { MyDelegate PropertyChanged = null; PropertyChanged += fun; }
//"DGID", "CLASS", "DGNAME", "STATUS", "CODE", "SOURCE", "MAXCOUNT" public async Task ConduitDefaults() { var tasks = new List <Task>(); using (var odw = new OracleDatabaseWorker(tbOracleConnectionStringText)) { List <string> conduitsizes = new List <string>() { "1" }; // odw.GetDistinctDataColumn(cabTable, "CABLESIZE"); List <string> conduitmedia = new List <string>() { "Media" }; List <string> conduittypes = odw.GetDistinctDataColumn(conTable, "TYPE");; List <string> conduitstatuses = odw.GetDistinctDataColumn(conTable, "STATUS"); //size var del = new MyDelegate((lst) => { using (var uow = new UnitOfWork(Tsdl)) { foreach (var str in lst.Where(s => s != "" && !uow.Query <ConduitSize>().Select(x => x.Count.ToString()).Contains(s))) { ConduitSize cs = new ConduitSize(uow) { Count = int.Parse(str), Code = str }; uow.CommitChanges(); } } return(true); }); IAsyncResult sizeres = del.BeginInvoke(conduitsizes, null, null); //type del = new MyDelegate((lst) => { using (var uow = new UnitOfWork(Tsdl)) { foreach (var str in lst.Where(s => s != "" && !uow.Query <ConduitType>().Select(x => x.TypeName).Contains(s)) ) { ConduitType cs = new ConduitType(uow) { TypeName = str }; uow.CommitChanges(); } } return(true); }); IAsyncResult typeres = del.BeginInvoke(conduittypes, null, null); //status del = new MyDelegate((lst) => { using (var uow = new UnitOfWork(Tsdl)) { foreach (var str in lst .Where(s => s != "" && !uow.Query <ConduitStatus>().Select(x => x.StatusName).Contains(s)) ) { ConduitStatus cs = new ConduitStatus(uow) { StatusName = str }; uow.CommitChanges(); } } return(true); }); IAsyncResult statusres = del.BeginInvoke(conduitstatuses, null, null); //media del = new MyDelegate((lst) => { using (var uow = new UnitOfWork(Tsdl)) { if (!uow.Query <ConduitClass>().Any(x => x.TypeName == "Class")) { ConduitClass cc = new ConduitClass(uow) { TypeName = "Class" }; uow.CommitChanges(); } foreach (var str in lst .Where(s => s != "" && !uow.Query <ConduitMedia>().Select(x => x.TypeName).Contains(s)) ) { ConduitMedia cs = new ConduitMedia(uow) { TypeName = str }; uow.CommitChanges(); } } return(true); }); IAsyncResult mediares = del.BeginInvoke(conduitmedia, null, null); await Task.FromResult(sizeres); await Task.FromResult(typeres); await Task.FromResult(statusres); await Task.FromResult(mediares); } }
static void Main(string[] args) { #region step3 // Den Delegaten einsetzen. MyDelegate delegateVariable = new MyDelegate(Addiere); // Delegaten ausführen int ergebnis = delegateVariable(5, 8); Console.WriteLine($"Das Ergebnis ist: {ergebnis}"); // Neuzuweisung der Variable delegateVariable = Subtrahiere; ergebnis = delegateVariable(5, 2); Console.WriteLine($"Das Ergebnis ist: {ergebnis}"); // Hinzufügen einer weiteren Methode zu der Variable delegateVariable += Addiere; // Ausgeführt werden die Methoden in glecher Reihenfolge wie sie hinzugefügt worden sind. // Aber nur den Return der letzten Methode können wir abfangen. ergebnis = delegateVariable(4, 4); Console.WriteLine($"Das Ergebnis ist: {ergebnis}"); #endregion Console.WriteLine(); #region Iteration of delegates foreach (var item in delegateVariable.GetInvocationList().ToList()) { Console.WriteLine(item.Method); } #endregion Console.WriteLine(); #region Delete Function from Delegate // Entfernen einer weiteren Methode zu der Variable delegateVariable += Addiere; foreach (var item in delegateVariable.GetInvocationList().ToList()) { Console.WriteLine(item.Method); } delegateVariable = null; #endregion Console.WriteLine(); #region eingebaute Delegaten Func <int, int, int> meinFunc = Addiere; meinFunc += Subtrahiere; Console.WriteLine(meinFunc(42, 35)); #endregion Console.WriteLine(); FühreAus(meinFunc); Console.WriteLine(); FühreAus(Addiere); #region Lists & Delegates Step 2 Console.WriteLine(); List <string> Städteliste = new List <string>() { "Karlsruhe", "Hamburg", "Bremen" }; string gefundeneStadt = Städteliste.Find(SucheStadtMitH); Console.WriteLine($"Die Stadt heißt: {gefundeneStadt}"); // Übergabe einer Methode als anonyme Methode gefundeneStadt = Städteliste.Find( delegate(string stadt) { return(stadt.StartsWith("K")); } ); Console.WriteLine($"Die Stadt heißt: {gefundeneStadt}"); // Übergabe einer Methode als Arrow Function / Pfeilfunktion / Lambda // Original //gefundeneStadt = Städteliste.Find((string stadt) => {return stadt.StartsWith("B"); } ); // Falls nur ein Argument können dir runden Klammern weg // Falls nur eine Anweisung dann return und {} weg gefundeneStadt = Städteliste.Find(stadt => stadt.StartsWith("B")); Console.WriteLine($"Die Stadt heißt: {gefundeneStadt}"); Städteliste = Städteliste.OrderBy(stadt => stadt[0]).ToList(); foreach (var item in Städteliste) { Console.WriteLine(item); } #endregion // Vorteil von Pfeilfunktionen // Wenn wir die Methoden Addieren vorhin nicht definiert hätten: meinFunc = (a, b) => a + b; Console.ReadKey(); }
public static void doSomething(MyDelegate <int> del) { Console.Out.WriteLine("the delegate returns: " + del(5)); }
static void ApplyDelegate(MyDelegate a, string x) { a(x); }