1: /////////////////////////////////////////////////////
2: //
3: // 總結所有的 New Features(language extensions)
4: //
5: /////////////////////////////////////////////////////
6:
7: using System;
8: using System.Collections.Generic;
9: using System.Linq;
10: using System.Text;
11: using System.Diagnostics;
12:
13: static class newFeaturesDemo
14: {
15: class ProcessData {
16: public Int32 Id { set; get; }
17: public Int64 Memory { set; get; }
18: public String Name { set; get; }
19: }
20:
21: public static void DisplayProcesses(Func<Process, Boolean> match) {
22:
23: // 1. implicitly typed local variables
24: var processes = new List<ProcessData>();
25:
26: foreach (var process in Process.GetProcesses()) {
27: if (match(process)) {
28:
29: // 2. object initialized
30: processes.Add(new ProcessData
31: {
32: Id = process.Id,
33: Name = process.ProcessName,
34: Memory = process.WorkingSet64
35: });
36: }
37: }
38:
39: // 3. extension methods
40: Console.WriteLine("Total memeory: {0} MB",
41: processes.TotalMemory()/1024/1024);
42:
43: // 4. lambda expression
44: var top2Memory = processes
45: .OrderByDescending(process => process.Memory)
46: .Take(2)
47: .Sum(process => process.Memory) / 1024 / 1024;
48:
49: Console.WriteLine(
50: "Memory consumed by the two most hungry processes: {0} MB",
51: top2Memory);
52:
53: // 5. anonymous type
54: var results = new
55: {
56: TotalMemory = processes.TotalMemory() / 1024 / 1024,
57: Top2Memory = top2Memory,
58: Processes = processes
59: };
60:
61: ObjectDumper.Write(results, 1);
62: ObjectDumper.Write(processes);
63:
64: }
65:
66: static Int64 TotalMemory(this IEnumerable<ProcessData> processes) {
67: Int64 result = 0;
68: foreach (var process in processes) {
69: result += process.Memory;
70: }
71:
72: return result;
73: }
74:
75: static void Main()
76: {
77: DisplayProcesses(
78: process => process.WorkingSet64 >= 20*1024*1024);
79: }
80: }
Post a Comment