[TestMethod] // ----------------------------------------------------------------------- public void TestMethod1() { var i1 = 10; // Implicitly typed. int i2 = 10; // Explicitly typed. HLog.print("i1={0}, i2={1}", i1, i2); // s is compiled as a string var s = "Hello"; // a is compiled as int[] var a = new[] { 0, 1, 2 }; // anon is compiled as an anonymous type var anon = new { Name = "Terry", Age = 34 }; // list is compiled as List<int> var list = new List <int>(); int[] nums = { 0, 1, 2, 3 }; foreach (var n in nums) { HLog.print($"n={n}"); } }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod4() { //Init一個Person物件 Person p = new Person() { Age = 10, Name = "Tom" }; #region Func // WAY1: // 宣告一個Func<Person,string>委託 funcPointer Func <Person, string> funcPointer; // Func<in Person, out string> // funcPointer委託指向CheckAge方法 funcPointer = new Func <Person, string>(CheckAge); // 執行funcPointer委託 (執行CheckAge方法) string result = funcPointer(p); //最後將結果顯示出來 HLog.print("result =" + result); #endregion // WAY2: 直接呼叫CheckAge就好了, 幹嘛透過Func<> ??? string result2 = CheckAge(p); // 解耦合, 有時候先定義好了funcPointer, 下面的實作需要被後來的人Impl for this funcPointer HLog.print("result2=" + result2); }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod5() // 字串插補$在建立格式化字串時,是比{0}功能更容易理解且方便的語法。 { // @ 字元將程式碼元素當成前置詞,編譯器要將此元素解譯為識別項,不是 C# 關鍵字。 // 下例會使用 @ 字元來定義名為專給 for 的識別項,它會用在 for 迴圈中。 string[] @for = { "John", "James", "Joan", "Jamie" }; for (int ctr = 0; ctr < @for.Length; ctr++) { HLog.print($"Here is your gift, {@for[ctr]}!"); } // The example displays the following output: // Here is your gift, John! // Here is your gift, James! // Here is your gift, Joan! // Here is your gift, Jamie! string filename1 = @"c:\documents\files\u0066.txt"; string filename2 = "c:\\documents\\files\\u0066.txt"; HLog.print(filename1); HLog.print(filename2); // The example displays the following output: // c:\documents\files\u0066.txt // c:\documents\files\u0066.txt string s1 = "He said, \"This is the last \u0063hance\x0021\""; string s2 = @"He said, ""This is the last \u0063hance\x0021"""; HLog.print(s1); HLog.print(s2); // The example displays the following output: // He said, "This is the last chance!" // He said, "This is the last \u0063hance\x0021" // c=0x0063 , !=0x0021 }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod3() // Func 混用時 { Func <int, int, int> add = Sum; // Func<in int , in int , out int> int result = add(12, 18); HLog.print("TestMethod6 result =" + result); }
public void FindBadGuys() { HLog.print("喂! 我是{0}", name); if (PoliceCatchThiefEvent != null) { PoliceCatchThiefEvent(); } }
public void TestMethod3() { var car = new Car(15); new Alerter(car); HLog.print("TestMethod2 !!!!!!!!!!!!"); car.Run(120); }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod2() { Timestwo mul_two = delegate(int x) { return(2 * x); }; // delegate 2.實作(注意函式名稱在原本type的位置) 3. 指定委派 Multiply mul = delegate(int x, int y) { return(x * y); }; HLog.print("TestMethod2 mul_two = " + mul_two(5).ToString()); // delegate 4. 使用 HLog.print("TestMethod2 mul = " + mul(5, 6).ToString()); }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod4() // 當使用new產生delegate函數時 { // 建立delegate物件 CompareDelegate cd = new CompareDelegate(Compare); // 2. 實作 & 3. 委派用 new Object 物件式寫法 // 呼叫delegate HLog.print("TestMethod4 = " + cd(1, 2)); }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod3() { FunctionToCall functionDelegate = Add2; // 5+2 functionDelegate += Add3; // 7+3 functionDelegate += Add2; // 10+2 HLog.print("Value: {0}", functionDelegate); // result= 12 }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod12() // 帶傳入參數Func<int,int,string> , 回傳類型為string 傳入參數為int,int { Calculate2 = Add2; HLog.print(Calculate2(6, 5)); //傳入型態為2個int 會執行 Add(5,6) //num1 + num2 = 11 Calculate2 = Sub2; HLog.print(Calculate2(6, 5)); //會執行 Sub(5,6) //num1 - num2 = 1 }
protected virtual void OnNumChanged() { if (changeNumEvent != null) { changeNumEvent(); // event triggering~~~~~ } else { HLog.print("Event not trigger"); } }
[TestMethod] // ----------------------------------------------------------------------- public async Task TestMethod2Async() { HLog.print("TestMethod2Async"); Task <int> downloading = DownloadDocsMainPageAsync(); Console.WriteLine($"{nameof(TestMethod2Async)}: Launched downloading."); int bytesLoaded = await downloading; Console.WriteLine($"{nameof(TestMethod2Async)}: Downloaded {bytesLoaded} bytes."); }
[TestMethod] // ----------------------------------------------------------------------- public void TestDelegate() { Operation op = delegate_Add; // delegate 3. 指定委派耦合 HLog.print("int ret=" + op(1, 2)); // delegate 4. 使用委派函數 // Tips: delegate的缺點, 因為type不同, 需要重新指定耦合, 而Func改善這個缺點了 OperationD opD = delegate_Add; // delegate 3. 指定委派耦合 double ret = opD(1.0, 2.0); // delegate 4. 使用委派函數 HLog.print("double ret=" + ret); }
public static void ShowValue(object o) { if (o is Human p) // KEY: is Type { HLog.print(p.Name); } else if (o is Dog d) { HLog.print(d.Name); } }
public void Run(int speed) { int distance = 0; while (Petrol > 0) { Thread.Sleep(100); Petrol--; // KEY: this value is monitoring by Alerter distance += speed; HLog.print("Car is running... Distance is " + distance.ToString()); } }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod4() // 字串插補$在建立格式化字串時,是比{0}功能更容易理解且方便的語法。 { string name = "Mark"; var date = DateTime.Now; // Composite formatting: HLog.print("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date); // String interpolation: HLog.print($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now."); // out: // Hello, Mark! Today is Wednesday, it's 19:40 now. }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod3() { GenericDelegate <int, int> myDelegate = new GenericDelegate <int, int>(Cal); // #3 實例 string res1 = myDelegate(3, 5); // #4 使用 HLog.print(res1); // Func+lambda 只要一行 #1,2,3 Func <int, int, string> func = (a, b) => (a + b).ToString(); string res2 = func(4, 6); // #4 使用 HLog.print(res2); }
public void TestMethod2() { var pub = new EventPublisher(); var sub1 = new Subscriber("sub1", pub); var sub2 = new Subscriber("sub2", pub); // Call the method that raises the event. ex: the user is clicking the button pub.DoSomething(); // Keep the console window open HLog.print("Pause..."); }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod3_var() { int[] testSet = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; var primes = testSet.Where(n => Factor(n).ToList() is var factors && // KEY: is var factors.Count == 2 && factors.Contains(1) && factors.Contains(n)); foreach (int prime in primes) { HLog.print($"Found prime: {prime}"); } }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod1() { // ?: operator // var value = expression1 : expression2; // example: int test = 10; int a = test > 0 ? 5 : -1; // if(test>0) a=5; else a=-1; /* * if (test > 0) * a = 5; * else * a = -1; */ HLog.print("a=" + a); // out: a=5 // value ?? expression // example: int?NullableValue = null; int b = NullableValue ?? -1; // if(NullableValue==null) b=-1; else b=NullableValue.Value; /* * if (NullableValue is null) * b = -1; * else * b = NullableValue.Value; */ HLog.print("b=" + b); // out: b=-1 // value ?.expression // example: int[] NullableArrayValue = null; int? c = NullableArrayValue?.Length; // if(NullableValue==null) c=null; else c=NullableValue.Value; /* * if (NullableArrayValue is null) * c = null; * else * c = NullableArrayValue.Length; */ HLog.print("c=" + c); // out: c= }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod1() { // 格式項目語法: // 每個格式項目都會使用下列格式,並由下列元件所組成: // { index[ , align][ : digit-format]} // ps.成對的大括號("{" 和 "}") 是必要的。 string name = "Fred"; HLog.print(String.Format("Name = {0}, hours = {1:hh}", name, DateTime.Now)); // 強制的 index 元件 (也稱為參數規範) 是用以識別物件清單中對應項目的數字 (從 0 開始) HLog.print(String.Format("numbers = {0}, {1}, {2}, {3}", 10, 11, 12, 13)); // out = 10, 11, 12, 13 // 多個格式項目可以藉由指定相同參數規範來參考物件清單中的相同項目。 // 例如,您可以指定複合格式字串(例如: "0x")來格式化十六進位、科學和數位格式的相同數值 {0:X} {0:E} {0:N} // D=Decimal , X=HEX , N=number , E=expermential , C=Currency HLog.print(String.Format("0x{0:X} {0:E} {0:N}", Int64.MaxValue)); // out = 0x7FFFFFFFFFFFFFFF 9.223372E+018 9,223,372,036,854,775,807.00 }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod1() { int[] nums = { 0, 1, 2, 3 }; foreach (var n in nums) { HLog.print("n=" + n); } var v = new { Amount = 108, Message = "Hello" }; // Rest the mouse pointer over v.Amount and v.Message in the following // statement to verify that their inferred types are int and string. HLog.print(v.Amount + v.Message); var anonArray = new[] { new { name = "apple", diam = 4 }, new { name = "grape", diam = 1 } }; }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod1() { // Declare instances of the custom delegate. CustomDel hiDel, byeDel, multiDel, multiMinusHiDel, addDel, removeDel; // In this example, you can omit the custom delegate if you // want to and use Action<string> instead. //Action<string> hiDel, byeDel, multiDel, multiMinusHiDel; // Create the delegate object hiDel that references the // method Hello. hiDel = Hello; // Create the delegate object byeDel that references the // method Goodbye. byeDel = Goodbye; // The two delegates, hiDel and byeDel, are combined to // form multiDel. multiDel = hiDel + byeDel; // Remove hiDel from the multicast delegate, leaving byeDel, // which calls only the method Goodbye. multiMinusHiDel = multiDel - hiDel; // add more delegates to list addDel = hiDel; // assignment required at fist time addDel += byeDel; // remove delegate from list removeDel = addDel; // assignment required at fist time removeDel -= byeDel; HLog.print("Invoking delegate hiDel:"); hiDel("A"); HLog.print("Invoking delegate byeDel:"); byeDel("B"); HLog.print("Invoking delegate multiDel:"); multiDel("C"); // KEY: call hi+bye at once. HLog.print("Invoking delegate multiMinusHiDel:"); multiMinusHiDel("D"); HLog.print("Invoking delegate addDel: +="); addDel("E"); HLog.print("Invoking delegate removeDel: -="); removeDel("F"); }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod1() { int num = 33; PrintNumber print; if (num % 2 == 1) { print = PrintOddNumber; } else { print = PrintEvenNumber; } print(num); HLog.print(num); }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod14() { // Create an array of Point structures. Point[] points = { new Point(100, 200), new Point(150, 250),new Point(250, 375), new Point(275, 395),new Point(295, 450) }; // Define the Predicate<T> delegate. Predicate <Point> predicate = FindPoints; // KEY: // Find the first Point structure for which X times Y is greater than 100000. Point first = Array.Find(points, predicate); // Point first = Array.Find(points, x => x.X * x.Y > 100000 ); // lambda // Display the first structure found. HLog.print("Found: X = {0}, Y = {1}", first.X, first.Y); }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod1_check_obj() { Object obj = new Human("Hawk"); ShowValue(obj); obj = new Dog("Corgi"); ShowValue(obj); if (obj is Animal) { HLog.print(" obj is Animal"); } else { HLog.print(" obj is NOT Animal XXXXXXXXXXX"); } }
[TestMethod] // ----------------------------------------------------------------------- public void TestFunc() { // Func<int,int,int> is a delegate which accepts two int parameters and returns int as a result Func <int, int, int> op; // Func 1.宣告 Func <double, double, double> opD; // Func 1.宣告 op = Func_Add; // Func 3.指定 HLog.print(op(1, 2)); // Func 4. 使用Func函數 opD = Func_Add; // Func 3.指定 double ret = opD(1.0, 2.0); // Func 4. 使用Func函數 HLog.print("double ret=" + ret); /* * // lambda * Func<int, int, int> op = (a, b) => a + b; // Func 1.宣告+2.實作+3.指定 * HLog.print(op(1, 2)); // Func 4. 使用Func函數 */ }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod3() { string FormatString1 = String.Format("{0:dddd MMMM}", DateTime.Now); string FormatString2 = DateTime.Now.ToString("dddd MMMM"); int MyInt = 100; HLog.print("{0:C}", MyInt); // out = $100.00 // 使用兩種不同方式來格式化一個物件 string myName = "Fred"; HLog.print(String.Format("Name = {0}, hours = {1:hh}, minutes = {1:mm}", myName, DateTime.Now)); // Name = Fred, hours = 11, minutes = 30 // 對齊用法 string myFName = "Hawk", myLName = "Wei"; int myInt = 100; string FormatFName = String.Format("First Name = |{0,10}|", myFName); string FormatLName = String.Format("Last Name = |{0,10}|", myLName); string FormatPrice = String.Format("Price = |{0,10:C}|", myInt); HLog.print(FormatFName); HLog.print(FormatLName); HLog.print(FormatPrice); HLog.print(); FormatFName = String.Format("First Name = |{0,-10}|", myFName); // 負數為靠LEFT對齊 FormatLName = String.Format("Last Name = |{0,-10}|", myLName); FormatPrice = String.Format("Price = |{0,-10:C}|", myInt); HLog.print(FormatFName); HLog.print(FormatLName); HLog.print(FormatPrice); // out= // ¤100.00 // Name = Fred, hours = 03, minutes = 05 // First Name = | Hawk | // Last Name = | Wei | // Price = | NT$100.00 | // // First Name = | Hawk | // Last Name = | Wei | // Price = | NT$100.00 | }
private static void showDice(object o) { const int MAX_DICE_VALUE = 6; Dice d = new Dice(); if (d is null) { throw new NullReferenceException(); } if (o is Dice && d.Roll() is MAX_DICE_VALUE) // KEY: is CONSTANT { HLog.print($"The dice roll is MAX number == {MAX_DICE_VALUE} !"); } else { HLog.print($"The dice number is {d.currentNumber}!"); } }
[TestMethod] // ----------------------------------------------------------------------- public void TestMethod8() // 有沒有Invoke似乎沒差? { MathCalculation add_1 = Calculator.AddNumbers; Func <float, float, double> add_2 = Calculator.AddNumbers; // Func MathCalculation divide = Calculator.DivideNumbers; var result = Calculator.AddNumbers(2, 3); HLog.print("init =" + result); result = add_1.Invoke(2, 3); HLog.print("add_1=" + result); result = add_1(2, 3); HLog.print("add_1=" + result); result = add_2.Invoke(2, 3); HLog.print("add_2=" + result); result = add_2(2, 3); HLog.print("add_2=" + result); result = divide(100, 3); HLog.print("divide=" + result); }