//---------------------------------------------------------------------------- // Copyright (C) 2013-2015 Fabrice HARROUET (ENIB) // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. // The author makes no representations about the suitability of this // software for any purpose. // It is provided "as is" without express or implied warranty. //---------------------------------------------------------------------------- using System; public delegate int MyDelegate(string s); public class MyObject { protected int _i; public MyObject(int i) { _i=i; } public static int f1(string s) { Console.WriteLine("f1(\"{0}\")",s); return 1; } public static int f2(string s) { Console.WriteLine("f2(\"{0}\")",s); return 2; } public int m1(string s) { Console.WriteLine("m1(\"{0}\")",s); return 1+_i; } public int m2(string s) { Console.WriteLine("m2(\"{0}\")",s); return 2+_i; } public MyDelegate anonymous() { return delegate(string s) { Console.WriteLine("{0} _i={1}",s,_i); return 1000+_i; }; } } public class Test { public static void Main(string[] args) { MyObject o1=new MyObject(10); MyObject o2=new MyObject(20); MyDelegate md; md=MyObject.f1; Console.WriteLine("{0}",md("AA")); md=MyObject.f2; Console.WriteLine("{0}",md("BB")); md=o1.m1; Console.WriteLine("{0}",md("CC")); md=o1.m2; Console.WriteLine("{0}",md("DD")); md=o2.m1; Console.WriteLine("{0}",md("EE")); md=o2.m2; Console.WriteLine("{0}",md("FF")); int localVar=100; md=delegate(string s) { Console.WriteLine("anonymous(\"{0}\")",s); return 3+localVar; }; Console.WriteLine("{0}",md("GG")); md=o1.anonymous(); Console.WriteLine("{0}",md("HH")); md=o2.anonymous(); Console.WriteLine("{0}",md("II")); } } //----------------------------------------------------------------------------