static void Main() { Person jon = new Person("jon"); StringProcessor jonsVoice, background; jonsVoice = new StringProcessor(jon.Say); background = new StringProcessor(Background.Note); jonsVoice.Invoke("hello"); jonsVoice.Invoke("hi"); background("air plane!"); }
private static void Main(string[] args) { var alphaNumbericCollector = new AlphaNumbericCollector(); var stringCollector = new StringCollector(); AlphaNumericProcessor += alphaNumbericCollector.ProccessString; StringProcessor += stringCollector.AddString; var rgx = new Regex(@"\d+"); string line; while (true) { line = Console.ReadLine(); if (string.IsNullOrWhiteSpace(line)) { break; } if (rgx.IsMatch(line)) { AlphaNumericProcessor?.Invoke(line); } else { StringProcessor?.Invoke(line); } } AlphaNumericProcessor -= alphaNumbericCollector.ProccessString; StringProcessor -= stringCollector.AddString; alphaNumbericCollector.PrintAll(); stringCollector.PrintAll(); Console.ReadKey(); }
static void Main(string[] args) { Console.WriteLine("\nSimple delegate use - listing 2.1\n"); Person john = new Person("John"); Person tom = new Person("Tom"); StringProcessor jonsVoice, tomsVoice, background; jonsVoice = new StringProcessor(john.Say); jonsVoice += new StringProcessor(tom.Say); jonsVoice += new StringProcessor(Background.Note); tomsVoice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); jonsVoice("Hey!"); tomsVoice.Invoke("Heyyy!"); background("Background message!"); // listing 2.3 string[] strings = new string[5]; object[] objects = strings; //objects[0] = john; object o = "str"; Console.WriteLine(o); Console.WriteLine(((string)o).Length); Console.WriteLine(o.ToString().Length); Console.WriteLine("\n\nLambda expressions, Func delegate type - listing 2.5\n"); Func <int, int, string> funcDel = (x, y) => (x * y).ToString(); Console.WriteLine(funcDel(5, 6)); Console.WriteLine("\n\nObject initialiser - listing 2.6\n"); Person jason = new Person() { Name = "Jason", Age = 25 }; Console.WriteLine("\n\nObject initialiser - listing 2.8\n"); int?x = null; x = 5; if (x != null) { int y = x.Value; Console.WriteLine($"y = {y}"); } int z = x ?? 10; Console.WriteLine($"z = {z}"); }
static void Main(string[] args) { string[] words = { "zero", "one", "two", "three", "four" }; int[] numbers = { 0, 1, 2, 3, 4 }; object[] allStrings = { "These", "are", "all", "strings" }; object[] notAllStrings = { "Number", "at", "the", "end", 5 }; List <User> users = new Users().UsersList; List <string> onlystring = users.SingleOrDefault().Details.ToLower().Split('\\').OfType <string>().ToList(); onlystring.ForEach(Console.WriteLine); //Creare o colectie enumerabil default ce nu contine nici un element //Initializare var enumInt = Enumerable.Empty <int>(); //Atribuire o lista de numere intregi enumInt = new List <int>() { 1, 2, 3 }; //Castarea elementului la o lista de int si afisarea elementelor (enumInt as List <int>).ForEach(Console.WriteLine); string[] asString = new string[0]; int index = asString.Length; foreach (object word in allStrings) { Array.Resize(ref asString, index + 1); asString[index] = (string)word; index++; } words.GroupJoin(asString, word => word[0], allString => allString[0], (word, matches) => word + ": " + string.Join(";", matches.ToArray())).ToList().ForEach(Console.WriteLine); //Procesare Complexa al unui fisier xml cu ajutorul LINQ to XML QueryXML(); Person jon = new Person("Jon"); Person tom = new Person("Tom"); StringProcessor jonsvoice, tomsvoice, background; jonsvoice = new StringProcessor(jon.Say); tomsvoice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); jonsvoice("Hello, son."); tomsvoice.Invoke("Hallo,dat!"); background("An airplane flies past."); Console.Read(); }
static void Main(string[] args) { StringProcessor proc1, proc2; Person person = new Person("s"); proc1 = new StringProcessor(person.Say); proc2 = new StringProcessor(BackGround.Note); proc1("I miss you m"); proc1.Invoke("I miss you m"); proc2("An airplane file past."); Console.ReadKey(); }
static void Main() { Person jon = new Person("Jon"); Person tom = new Person("Tom"); StringProcessor jonsVoice, tomsVoice, background; jonsVoice = new StringProcessor(jon.Say); tomsVoice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); jonsVoice("Hello, son."); tomsVoice.Invoke("Hello, Daddy!"); background("An airplane flies past."); }
private static void DelegateTest() { Person jon = new Person("Jon"); Person tom = new Person("Tom"); StringProcessor jonsVoice, tomsVoice, background; jonsVoice = new StringProcessor(jon.Say); ///创建三个委托实例 tomsVoice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); jonsVoice("Hello, son."); //调用委托实例 tomsVoice.Invoke("Hello, Daddy"); //Invoke同步调用 //异步调用使用BeginInvoke和EndInvoke background("An airplane flies past"); }
static void Main(string[] args) { Person jon = new Person("Jon"); Person tom = new Person("Ton"); StringProcessor jonsVoice, tomsVoice, background; jonsVoice = new StringProcessor(jon.Say); jonsVoice += new StringProcessor(tom.Say); tomsVoice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); jonsVoice("Hello,son."); tomsVoice.Invoke("Hello,Daddy!"); background("An airplan flies past."); Console.ReadLine(); }
public void Main() { StringProcessor proc1, proc2; proc1 = new StringProcessor(StaticMethods.PrintString); InstanceMethods im = new InstanceMethods(); proc2 = new StringProcessor(im.PrintString); proc1("hello from static method"); proc2("Hello from instance method"); proc1.Invoke("hello from static method via invoke"); proc2.Invoke("hello from instance method via invoke"); }
public static void Run() { Person jon = new Person("Jon"); Person tom = new Person("Tom"); StringProcessor jonVotice, tomVotice, background; ////创建三个委托实例 jonVotice = new StringProcessor(jon.Say); tomVotice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); ////调用委托实例 jonVotice("Hello,son"); tomVotice.Invoke("Hello,Dayy!"); background("An airplance files past."); }
static void Main(string[] args) { var prasad = new Person("Prasad"); var rajveer = new Person("Rajveer"); var prasadSays = new StringProcessor(prasad.Say); // instance method var rajveerSays = new StringProcessor(rajveer.Say); // instance method var background = new StringProcessor(StaticMethods.Say); // static method prasadSays.Invoke("Look son, it's an aeroplane"); // calling instance method using Invoke rajveerSays("Ohh yes!"); // syntactic sugar i.e. without Invoke background("An aeroplane flies past."); // static method [can be called with/without invoke] Console.ReadLine(); }
static void Main() { Person jon = new Person("Jon"); Person tom = new Person("Tom"); StringProcessor jonsVoice, tomsVoice, background; jonsVoice = new StringProcessor(jon.Say); tomsVoice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); jonsVoice("Hello, son."); tomsVoice.Invoke("Hello, daddy."); background("An Airplane flies past."); // Delegates refer to the instance in the state when it is invoked, not the state when created jon.Name = "Bill"; jonsVoice("What is my name?"); }
public static void Test() { Person p1 = new Person("Andy"); Person p2 = new Person("Tom"); StringProcessor andyvoice, tomvoice, background; andyvoice = new StringProcessor(p1.Say); tomvoice = new StringProcessor(p2.Say); background = new StringProcessor(Background.Note); andyvoice("is the best"); tomvoice.Invoke("is not really good"); background("bull shit"); }
public static void Example() { // Create Delegate StringProcessor proc1, proc2, proc3; Delegates instance = new Delegates(); proc1 = new StringProcessor(instance.PrintString); // Instance proc3 = new StringProcessor(instance.PrintObject); proc2 = new StringProcessor(Delegates.PrintStringStatic);// Static Console.WriteLine("!!!---11---!!!"); //Invoke delegate // simple proc1("Hello"); //full form proc3.Invoke("Hello 2"); }
public static void Demo() { StringProcessor proc1, proc2; /*proc1 = new StringProcessor(StaticMethods.PrintString); * InstanceMethods instance = new InstanceMethods(); * proc2 = new StringProcessor(instance.PrintString); */ Person jon = new Person("Jon"); Person tom = new Person("Tom"); StringProcessor jonsVoice, tomsVoice, background; jonsVoice = new StringProcessor(jon.Say); tomsVoice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); jonsVoice("Hello, son."); tomsVoice.Invoke("Hello, Daddy!"); background("An airplane flies past."); }
static void Mains()//要用的时候改成Main { //委托区 Person jon = new Person("Jon"); Person tom = new Person("Tom"); StringProcessor jonsVoice, tomsVoice, background; jonsVoice = new StringProcessor(jon.Say); //3.必须创建一个委托实例 jonsVoice += jon.Say2; //合并委托、订阅委托 jonsVoice -= jon.Say2; //移除委托、取消委托 tomsVoice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); jonsVoice("Hello");//4.必须调用委托实例 tomsVoice("there"); tomsVoice.Invoke("there2"); background("I'm BG"); Console.ReadLine(); }
static void Main(string[] args) { StringProcessor p = new StringProcessor(PrintString); p += PrintObject; p("String"); Person jon = new Person("Jon"); Person tom = new Person("Tom"); StringProcessor jonVoice, tomVoice, background; jonVoice = new StringProcessor(jon.Say); tomVoice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); jonVoice("Hello,Jon!"); tomVoice.Invoke("Hello,Tom!"); background("An airplane files past.."); Console.ReadLine(); }
public static void main() { // The word delegate is often confusing used to describe both the delegate type and the delegate instance. // But the distinction between the two is exactly the same as between any other type and instances of that type. // STEP THREE: CREATE AN INSTANCE OF THE DELEGATE TYPE, SPECIFYING WHICH METHOD (THE ACTION) WILL BE EXECUTED WHEN THE DELEGATE INSTANCE IS INVOKED. StringProcessor sp1 = new StringProcessor(doSomething); // When the ACTION in an instance method, you need an instance of the type. This object instance is called the TARGET of the ACTION. // When the delegate instance is invoked, the ACTION will be invoked on the TARGET. // A delegate instance will prevent its target from being garbage collected if the delegate instance itself is collected. // This will result in memory leaks: a long-lived object indirectly holds a reference to short-lived one, prolonging its lifetime. DelegateExample de = new DelegateExample(); StringProcessor sp2 = new StringProcessor(de.doSomethingElse); // STEP FOUR: INVOKE THE DELEGATE INSTANCE Console.WriteLine("Invoking delegate instance sp1 returns {0}", sp1.Invoke("leon")); // Invoking a delegate without using an explicit call of the Invoke method. Console.WriteLine("Invoking delegate instance sp2 returns {0}", sp2("LEON")); sp2 += sp1; Console.WriteLine("Invoking multicasted delegate instance sp2 returns {0}", sp2("LEON")); StringProcessor sp3 = new StringProcessor(de.doSomethingElse); }
public void VariousWaysToInvokeDelegate() { StringProcessor del = DelegateActions.ToUpperCaseStatic; var input = "test"; var expectedOutput = "TEST"; var directCall = del(input); Assert.AreEqual(expectedOutput, directCall); var standardInvoke = del.Invoke(input); Assert.AreEqual(expectedOutput, standardInvoke); var dynamicInvoke = del.GetInvocationList()[0].DynamicInvoke(input); Assert.AreEqual(expectedOutput, dynamicInvoke); var asyncResult = del.BeginInvoke(input, null, null); var asyncInvoke = del.EndInvoke(asyncResult); Assert.AreEqual(expectedOutput, asyncInvoke); }
static void Main(string[] args) { Person ismael = new Person("Ismael"); Person allen = new Person("Allen"); StringProcessor ismaelVoice, allenVoice, background; // 4) create delegate instances ismaelVoice = new StringProcessor(ismael.Say); // 5) invoke delegate instances allenVoice = new StringProcessor(allen.Say); background = new StringProcessor(Background.Note); ismaelVoice("Hello, son..."); allenVoice.Invoke("Hello, Daddy!"); background("An airplance flies past."); //anonymous types var jon = new { Name = "Jon", Age = 12 }; var tom = new { Name = "Tom", Age = 12 }; jon = tom; Console.WriteLine(" Name: {0} , Age: {1}", jon.Name, jon.Age); Console.ReadLine(); }
static void Main(string[] args) { EnumSample es = new EnumSample(); es.Test(); System.Console.WriteLine(new structSample(12, 22).Diagnoal); structSample ss = new structSample(1, 2); // ss.Length = 11; //ss.Width = 22; System.Console.WriteLine(ss.Diagnoal); System.Console.WriteLine(StaticClass.cc); Person jon = new Person("Jon"); StringProcessor jonsVoice, tomsVoice, background; jonsVoice = new StringProcessor(jon.Say); { Person tom = new Person("Tom"); tomsVoice = new StringProcessor(tom.Say); } background = new StringProcessor(Background.Note); jonsVoice("Hello, son."); tomsVoice("hello, Daddy"); background("An airplane flies past"); jon.Name = "Jon Snow"; jonsVoice += tomsVoice; foreach (Delegate dele in jonsVoice.GetInvocationList()) { dele.DynamicInvoke("Iknow nothing yegret"); } jonsVoice("I know nothing"); background.Invoke("Another airplane files past"); ClassSizeof szof = new ClassSizeof(name: "zhouwei", age: 33, gender: "male"); // Program pro = new Program(); //class Console.WriteLine("{0}-{1}-{2}", szof.Name, szof.Age, szof.Gender); Console.WriteLine(Marshal.SizeOf(szof /*new ClassSizeof(name: "zhouwei", age: 33, gender: "male")*/)); List <ClassSizeof> list = new List <ClassSizeof> { new ClassSizeof(name: "zhouwei", age: 33, gender: "male"), new ClassSizeof(name: "zhouchao", age: 30, gender: "male"), new ClassSizeof(name: "zhoujiazu", age: 230, gender: "male"), new ClassSizeof(name: "dengmin", age: 32, gender: "female") }; list.Sort(new Comparer()); list.Sort(delegate(ClassSizeof s1, ClassSizeof s2) { return(s2.Age - s1.Age); }); list.Sort(comparison: (a, b) => { return(a.Age - b.Age); }); foreach (ClassSizeof szof2 in list.OrderBy(z => z.Name)) { Console.WriteLine("{0}-{1}-{2}", szof2.Name, szof2.Age, szof2.Gender); } foreach (ClassSizeof szof1 in list) { Console.WriteLine("{0}-{1}-{2}", szof1.Name, szof1.Age, szof1.Gender); } Predicate <ClassSizeof> gr30 = delegate(ClassSizeof sz) { return(sz.Age > 30); }; List <ClassSizeof> qualified = list.FindAll(gr30); Action <ClassSizeof> print = Console.WriteLine; Console.WriteLine("action print"); qualified.ForEach(print); var qua = from ClassSizeof sz in list where sz.Age > 30 select sz; Console.WriteLine("LINQ"); foreach (ClassSizeof sz in qua.OrderBy(p => p.Age)) { Console.WriteLine(sz); } DelegateEventsTest det = new DelegateEventsTest(); det.Test(); GenericDictionary td = new GenericDictionary(); td.Test(); PartialClassSampleInvoker pcsi = new PartialClassSampleInvoker(); pcsi.Test(); ExtensionClass ec = new ExtensionClass(); ec.Test(); OverrideAndHiddenSample oahs = new OverrideAndHiddenSample(); oahs.Test(); AsAndIsSample aais = new AsAndIsSample(); aais.Test(); WeakReferenceSample srs = new WeakReferenceSample(); srs.Test(); LinkedListSample lls = new LinkedListSample(); lls.Test(); CoContraVarianceIsMakeSureConvertFromDerivedToBase iovs = new CoContraVarianceIsMakeSureConvertFromDerivedToBase(); iovs.Test(); Console.Read(); }
static void Main(string[] args) { //使用委托 Person jon = new Person("Jon"); Person tom = new Person("Tom"); StringProcessor jonsVoice, tomsVoice, background; //创建3个委托实例 jonsVoice = new StringProcessor(jon.Say); tomsVoice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); jonsVoice("Hello, son"); tomsVoice.Invoke("Hello,Daddy"); //一般情况下不需要显示调用。 background("An airplane flies past"); //C# 2中对于委托的改进 //C# 1当中的写法 EventHandler handler; handler = new EventHandler(HandleDemoEvent); handler(null, EventArgs.Empty); //C# 2中使用隐式委托实例 handler = delegate(object sender, EventArgs e) { Console.WriteLine("Handled anonymously"); }; handler(null, EventArgs.Empty); //C# 2中使用匿名方法的简写形式 handler = delegate { Console.WriteLine("Handled anonymously again"); }; handler(null, EventArgs.Empty); //C# 2使用委托的逆变性 //.NET Core中不可用 //MouseEventHandler mouseEventHandler = HandleDemoEvent; //mouseEventHandler(null, new MouseEventArgs(MouseButtons, None, 0, 0, 0, 0)); //C# 3中,使用Func委托类型以及Lambda表达式的例子 Func <int, int, string> func = (x, y) => (x * y).ToString(); Console.WriteLine(func(5, 20)); //C# 3中引入的匿名类型 var jon2 = new { Name = "jon", Age = 31 }; var tom2 = new { Name = "Tom", Age = 4 }; Console.WriteLine("{0} is {1}", jon2.Name, jon2.Age); Console.WriteLine("{0} is {1}", tom2.Name, tom2.Age); jon2 = tom2; //编译器根据声明的字段,推断出了他们具有相同的类型。所以可以使用赋值。 //C# 4当中引入了动态类型 dynamic o = "hello"; Console.WriteLine(o.Length); o = new string[] { "hi", "there" }; Console.WriteLine(o.Length); //C#2的可空类型 int?x2 = null; x2 = 5; if (x2 != null) { int y = x2.Value; Console.WriteLine(y); } int z = x2 ?? 10; //使用null联合操作符 Console.WriteLine(z); }