C#從零開始_自學C#、Visual Studio實境秀 40/ Getting Started with C# Lesson 8~11 of ...



{

VBA 物件類別模組 Class Modules



6:20 Lesson 8 of 20 Looping a Known Number of Times http://bit.ly/2up94VD

{6:55 Nested Loops 巢狀的迴圈

控制迴圈次數的變數 control variables :When creating basic for loops using this approach, the loop control variables are conventionally named, in sequence, i, j, k.

如果迴圈層級太多,就要考慮了:If you need more than three levels of nested for loops in your program, it's probably worth reconsidering your design or extracting some of the logic out into another method.

24:00 人性化、可讀性高才好 Take care to choose good names for your variables, as this greatly improves the readability and maintainability of your programs.

26:00 the PadLeft(3) method is used to add spaces to the beginning of a string until it reaches a certain length (in this case, 3).

30:00 afterthought expression

33:40 [Ctrl]+c Ctrl+c ctrl+pause(break) 一樣都可以讓一個無窮迴圈 infinite loop 停止。

41:00 練習成功

}

42:15 Lesson 9 of 20 Working with Arrays and Collections http://bit.ly/2vALV15

{

43:30 an array data structure.

陣列宣告時一定要指定類別:Arrays must be declared by specifying the type of its elements.

宣告陣列時並不一定要指定其大小:When declared, arrays do not need to specify a size, , but when assigned, they must have a fixed size.

隱含地宣告陣列:int[] otherIntegers = new [] { 1, 3, 5, 7, 9 }; // you can omit `int` and just specify []; type is inferred

49:00 You can think of an array as being like an egg carton or pill organizer. A weekly pill organizer typically has 7 spaces of equal size, while an egg carton has two rows of 6 spaces each. Array locations are often referred to as cells.

50:00 中括號和陣列:values are accessed by passing the index to the array using square braces ([ ]).

51:10 多維陣列 multi-dimensional array

51:40 確實多維陣列的每個元素可以儲存多個值: A multi-dimensional array can store multiple values for each element.

看是幾維(其每個元素)就儲存幾個值

二維陣列 三維陣列 Two-dimensional arrays are often thought of like a grid; three-dimensional arrays like a cube.

int[,] eggCarton = new int[2,6]; // a typical egg carton can be thought of as a 2x6 array

55:00 jagged arrays

C# also supports jagged arrays, which are multi-dimensional arrays in which each element is itself an array of variable length.

int[][] jaggedArray = new int[4][]; // define first dimension

jaggedArray[0] = new int[2] { 1, 2 }; // set values of first array

1:10:40 Arrays implement the IEnumerable interface,

1:14:30 提到 陣列 的 size 一般都是指其元素量:the size of the array 1:20:00 You can check the array's Length property to see its size. 所以 size 和 length 在陣列裡是一樣的概念 Remember its maximum index will always be one less than its length. 在 C# 才是如此,在VBA,則是一樣,在宣告時,要多少成員(元素)就是多少 length。如 array(0),則只有一個成員,array(1),則是2個。則其值是與 index 一致的。 如 UBound() 傳回的,也一樣是陣列最高的索引值(index) http://bit.ly/2twje3K 這裡 steve 老師是專指 C#的 array.length

1:18:20 動態陣列 其實也如 String 物件一樣,只是另外建構一個新的執行個體,並不是真的抹去原來或改變原來的陣列  If you are working with an array and need it to store more values than it currently has space for, you must declare a new array with enough space and populate it from the old array.

1:20:40 array 陣列其實是比較文雅、文士的翻法,而數組則比較白話、市民。陣列是用古文古兵法兵陣的概念來翻的,數組則是由數理的概念來翻的。

1:35:15 陣列與字串處理 Arrays and Strings

You can quickly create arrays from strings using the String.Split method.

1:37:30 delimiter separator

1:38:30 原來 CSV 是這個意思:comma-separated values, or CSV, is a common data transfer format.

string input = "red,blue,yellow,green";

string[] colors = input.Split(','); // note single quotes, which are used to define literal character (``char``) values

2:00:00 單引號 與 雙引號 還是有區別的!

2:24:00 可能是 char 要用單引號 而 string 則要用雙引號

3:40:00 將分離的文字組合起來:The reverse of this operation is the Join method

3:43:10 陣列在 C# 裡是一種 class Arrays are a built-in C# type with a lot of utility,

3:45:00 list 和 array 的關係 .ToList() :there may be other behavior available to other collection types that you would like to take advantage of. One last very common extension method you can apply to arrays is ToList. This method does just what you would expect - it creates a new List type and initializes it with the current contents of the array.

3:46:10 List 也是一種 class : a new List type

Lists .NET includes support for a variety of collection types, including the most commonly used List type.

a generic List<T>: 泛型就是不一定指定哪一類型都能用:you'll want to work with a list of a particular type of item, so you'll declare a generic List<T>, where T in this case is the type of objects the list will hold.

When you refer to a List<T> verbally, you'll say "a list of T", which makes sense since that really is what it represents.

A List<int> is a list of ints. A List<Customer> is a list of customers.

LIst<T> 就是同類(T)相聚、物以類聚 your program will raise an exception if you try to add an element to the list that isn't of the declared type.

List 和 array 的區別,就在於一個長度(size or length)是不固定的,一個是固定的:Lists do not have a fixed size.  This makes them more flexible than arrays.

4:33:00 當不確定所需大小時,可以先用 list 再用 ToArray() 轉成 array 來用 :If you don't know up front how many elements you need, you can first create and populate a list, and then call ToArray to produce the array.

除非記憶體容量不夠,否則理論上 List 的容量是沒有上限的:Unless the computer running your code runs out of memory, you can always add another element to a List.

using System.Collections.Generic:Generic lists are defined in the System.Collections.Generic namespace; you may need to add a using statement

3:54:30 Lists 的宣告:Declaring Lists

List<int> someInts = new List<int>(); // declares an empty list

someInts.Add(2);  // the list now has one item in it: {2}



List<int> moreInts = new List<int>() { 2, 3, 4 }; // you can initialize a list when you create it



string[] colors = "red,blue,yellow,green".Split(','); // an array of 4 strings

List<string> colorList = new List<string>(colors); // initialize the list from an array

3:56:10 You can add items to an existing list using the Add method. You can add a group of items all at once by using the AddRange method, You can add items to an existing list using the Add method. You can add a group of items all at once by using the AddRange method, 4:27:00 4:31:30

可以加入,也可以移除、插入任何元素(成員)進去:You can also remove items from a list using a variety of methods, and insert items anywhere within the current list.

List<string> colors = new List<string>() { "black", "white", "gray" };

colors.Remove("black"); //就其 name 、 value 來選擇

colors.Insert(0, "orange"); // orange is the new black

colors.RemoveAll(c => c.Contains("t")); // removes all elements matching condition (containing a "t")

// colors currently: orange, gray 選擇性辦案,差別待遇

colors.RemoveAt(0); // removes the first element (orange) 就其 index 、 position 來選擇

int numColors = colors.Count; // Count currently is 1

colors.Clear(); // colors is now an empty list 格殺勿論,一視同仁

4:04:10 ForEach method:

var colors = new List<string>() { "blue", "green", "yellow" };

colors.ForEach(Console.WriteLine); // equivalent to ForEach(c => Console.WriteLine(c)) 其實 .Foreach() 應屬委派的實例( instance) delegate  果然是委派  public delegate void Action();

4:14:00 4:19:00 知其所以然 就好理解了

4:15:10 To quickly create a string from a list of values, you can use the String.Join method:

4:20:30 if you need to create an array from a list, you can call the ToArray method.

4:38:40 專業有專業的文言文嘛!

4:40:30 Substring()

4:40:00 5:07:40 練習成功

{

using System;

using static System.Console;

using System.Collections.Generic;



namespace ConsoleApplication

{

public class Program

{

public static void Main()

{

string cmd = "";

string beh = String.Empty;

string it = String.Empty;

List<string> s = new List<string>() { "reading","cook"};

while(s.Count<5||s.Count==0)

{

Write("Enter command (+ item, - item, or -- to clear");

WriteLine();

cmd = ReadLine();

if (cmd == "--")

{

s.Clear();

s.ForEach(x => WriteLine(x));

break;

}

beh = cmd.Substring(0, cmd.IndexOf(" "));

it = cmd.Substring(cmd.IndexOf(" ") + 1);

switch (beh)

{

case "+":

s.Add(it);

break;

case "-":

s.RemoveAll(x=>x.Equals( it));

break;

}

//s.ForEach(WriteLine);

s.ForEach(z => WriteLine(z));

WriteLine();

}

}

}

}

}

}

5:10:10 Lesson 10 of 20 Looping Through Members of a Collection http://bit.ly/2uSepG0

{

Using the foreach Loop 。前面是 List<t> 的 foreach() 方法 5:24:45 You may recall from the previous lesson that the List type includes a similarly-named method, ForEach, that works very similarly to this loop (hence the name).

foreach 裡面的 in 後面接的是 collection 的 name ,就好像委派裡頭要用的是 method 的 name; 我此所稱的 name ,其實就是 一個 識別字 identifier

the in keyword is specified, followed by the collection to be iterated over (myList)

Lists 果然也是個 class :However, the foreach loop statement works on other collection types, not justs lists.

In fact, you can use the foreach loop on any type that implements IEnumerable (or its generic equivalent, or, more accurately, any type that has a GetEnumerator() method), which includes a wide variety of collection types (and arrays).

For example, to echo back to the user the arguments they passed to a console application, you could use foreach over the args array:

陣列也是個 class ,也需要去實例化 instantiated

  public static void Main(string[] args)

{

args =new string[]{ "g","d","b"};

foreach (var arg in args)

{

Console.WriteLine(arg);

}

}

5:33:50 The foreach loop is a very simple way to work with every element in a collection. It doesn't require access to an indexer for the collection,

5:35:55 Other looping techniques

5:37:00 length 是 array; count 是 collection 的。

5:47:00 也可以用 while 來存取集合中的任一分子(元素、成員 members elements):

var myList = new List<int>() { 10, 20, 30 };

int index = 0;

while (index < myList.Count)

{

Console.WriteLine(myList[index]);

index++;

}

5:49:00 練習 Next Steps 完成:

using static System.Console;

namespace ConsoleApplication

{

public class Program

{

public static void Main()

{

int[] ints = new int[] { 2, 4, 6, 9, 10, 111, 235, 582 };

int i = 0;int sum=0;

while ( i < ints.Length)

{

sum += ints[i];

i++;

}

WriteLine($"{sum}");

}

}

}

}

5:58:40 Lesson 11 of 20 Defining and Calling Methods http://bit.ly/2eJRaaM

{6:00:00 認識一下私淑老師群

6:08:25 A method is a function that is associated with a class.  C# 的方法 就是 VB 的 Function Functions (and therefore methods)  In this lesson, you'll see methods and functions generally referred to interchangeably. 即一個同義詞

6:12:10 Declaring Methods 宣告方法

There are two main kinds of methods in C#: static methods and instance methods.

6:14:10 A static method is global to the program, 靜態方法一定是 public ?

Instance methods are attached to an object instance.They can only be called if they are invoked from a non-null instance of an object of the appropriate type. Two

可見 invoke 和 call (off) 有差別

static methods 是用 call ; instance methods 是用 invoke;

6:18:40 Two objects of the same type will run the same code for a given instance method, but each method will have access to that object's internal state, so the results may be very different.

6:39:00 If you're writing a method that will only operate on the parameters being passed into it, you can typically declare it as a static method. Otherwise, your methods should be instance methods (which is the default if you don't add the static keyword).

所以有參數的方法,應該是 static

6:25:10 static methods 比較像方法(函數、函式)本身,需要做某些計算或操作的;而 instance methods 則比較像「行為」因為它附屬於某一個執行個體!

6:28:30 Naming Methods 為方法命一個好名:

Methods do things, so typically their names should include verbs that describe the action they perform.

Methods should be small and focused. 制心一處,無事不辦

6:38:30 Don't Repeat Yourself (DRY) principle

6:56:00 在 C# 中 methods有 return 傳回值,有不傳回值的,傳回值的就如同 VBA 裡的 Function(),而不傳回值的,就是 Sub();所以二者有沒有參數,都要加 parentheses 圓括號.

7:02:50 Return Types

7:15:40 Methods can only return a single result, which sometimes presents a challenge when designing how a program will work, especially when considering edge cases.

現在 c# 7 可以傳回 multiple results : Tuples  see : Tuples, 能讓你更容易的一次傳回多筆結果,

7:29:00 methods that need to return complex results should be modified in one of two ways.

7:39:00 7:41:00 to create a new class whose only role is to represent the result of a particular operation (often such classes are named with Result as a suffix):

Keep in mind when you're deciding how to return results from your methods that sometimes it will make sense to create a new class whose only role is to represent the result of a particular operation (often such classes are named with Result as a suffix). In most cases, it's better to use a result type that can accurately and fully describe the result of a function's action than to use out parameters for this same purpose.

8:15:00 把參數也作成物件類別,也是好的思考方向:As with the recommendation to use specialized objects for Result types, you may sometimes find that it makes sense to create objects to represent parameters as well

8:17:00 , or even to create a new type for a method to live on that eliminates the need to pass it many parameters (in such cases, the type's properties would typically be used instead of parameters).

7:20:00 In .NET programming, it's recommended you avoid returning error codes from your methods, and instead raise exceptions if necessary when errors occur.

要盡量利用 exceptions 物件,不要自訂錯誤表述



7:44:10 Parameters

7:45:10 選擇性參數 C# supports optional parameters which will use default values when omitted.

8:20:00 選擇性參數的設定方法:Parameters can be made optional by supplying them with default values.

7:46:30 You can even create methods that take an arbitrary number of parameters by using a params array, but some of these behaviors are more advanced than you need to know for this lesson.

8:32:30 和VBA一樣,選擇性參數在宣告時也要放在最後面:Note that required parameters must be declared before any optional parameters.

7:48:00 params (C# 參考) http://bit.ly/2tFixcR 參數的數量是可變動的

7:53:40 單引號 char 雙引號 string

public static void UseParams2(params object[] list) // object 所以 int char string 皆可

{

for (int i = 0; i < list.Length; i++)

{

Console.Write(list[i] + " ");

}

Console.WriteLine();

}

UseParams2(1, 'a', "test");

或許用此就可簡化或合併 (abstraction automation Don’t Repeat Yourself DRY http://bit.ly/2vUZeZD ) 我之前 VBA 裡數個類似的 Functions 卻有不同數量的參數

8:05:00 方法簽章 The name of a method, combined with the types of its parameters, must be unique within the class to which the method belongs. This is known as as the method's signature.

8:08:00 只要同名方法其參數的型別或數量不同,即可。 if you have two methods with the same name and set of parameter types, even if the return types are different or the parameers have different names.

8:09:00 多載 overloading 和方法簽章:It is possible to repeat the same name for a method, but when doing so each signature must be unique. These are referred to as method overloads

8:12:00 中文底子要好,不是光英文好就好 就能翻譯得好

8:13:00 盡量讓方法 單一化、單純化 It's a good idea to limit the number of parameters a method accepts, since a large number of parameters often indicates a method is doing too much and should be broken up into smaller methods.

8:33:40 Overloads 多載 有了選擇性參數,不一定要用多載: In many cases, this feature was used to support cases that are now better supported by optional parameters (a more recent C# language feature).

8:36:00 In any case, you can create method overloads to provide a richer interface for programmers, allowing them to choose the method signature that is best-suited to their needs.

8:59:00 Sometimes, you want to help programmers who might use your method by eliminating the need for them to convert whatever type they have into the type your method expects as a parameter. Thus, you create multiple overloads that will perform the type conversion internally.

This makes your method easier to use, and reduces the complexity of the code that calls it.

This kind of simplification is a key benefit your programs can get from the method overloading feature in C#.

9:01:30 更人性化,更好使用,更不容易出錯,更好維護:Remember to think about how you or other developers will use the methods you write. Try to write them so they're simple and easy to use and understand.

也就是活化方法,使其應用面更廣、更靈活。

9:02:55 Lambda Expressions

9:04:00 原來 lambda 也是一種方法: lambda expressions, a very special type of method.

9:04:55 lambda 只能寫在一行中: Lambda expressions are a type of method created in-line in your code.

9:06:00 原來就是因為 lambda 就是方法的一種 難怪在 List<T> 的 .ForEach()方法(委派)引數裡可以用方法名稱或 lambda expression

you will pass them as a parameter to other methods.

9:08:00 可以把方法存在一個變數裡:In C#, you're allowed to store methods inside of variables

Func<int, int> addOne = x => x + 1; // this is the lambda expression

Console.WriteLine(addOne(4));  9:13:00

9:15:00 lambda 表達式由二個部分組成:lambda expression, which has two parts.

The (=>) is a special operator for lambda expressions splitting the method parameters from the code to execute.

Since the lambda expression is only one line, the result of that one line is the return value (there is no need for an explicit return statement).

lambda => 右邊即是要 return 的值。就是因為 lambda 表達式只能寫一行的緣故

const int four = 4;

Func<int, int> addOne = x => x + 1;//也可寫成 Func<int, int> addOne = (x) => (x) + 1; 所以 () 其實就是方法的 parentheses ()嘛,所以內含的就是參數

Func<int, int, int> calcArea = (x,y) => x * y; // two parameters 用逗號區別各個參數,好像陣列元素的表示法

Func<int> twentyFive = () => calcArea(addOne(four), addOne(four)); // no parameters  沒有參數,所以仍有 () parentheses,更足見 () 即表參數

Console.WriteLine(twentyFive());  9:23:50 9:28:00 足見 lambda 其實就是一種特殊的方法表述式!!(就是省略了方法名稱!只保留,方法的參數--含沒有參數--即只留括號) 所以像 addOne = x => x + 1 這種式子,就是 addOne = 方法(x) => { return x + 1} 所以 Expression Bodied member 為什麼叫 expression 就是因為它是 lambda expression 嘛。

所以 lambda expression 其實就是把大括號 curly braces 省略且多行併作一行的表示法嘛!所以要理解 lambda expression 時,只要把它的還原為大括號和多行 就好理解了。 有時名稱會省略,有時不會。參見示例:http://bit.ly/2uA3HnN

可以把 => 這個符號 operator 看成 {} 就好理解了!{}是便於表述多行,而併作一行,就用 => 來表示了

還要注意, lambda expression 只能用在簡單,並非複雜的多行 statement/instruction .所以才能簡化成一行來表述

9:41:00 Lambda expressions can be very useful in describing simple functions. 不見題目只見關鍵字 simple 是關鍵字

9:42:00 9:44:55 Two ways in which they are commonly used is for predicates and selectors, which return a bool and an object respectively. You'll see these in action in Introducing LINQ, the lesson covering language integrated queries (LINQ).

9:45:55 Extension Methods 擴充方法 擴充的受詞是 class 把 class 的 members( methods) 擴充了(好像不是哦!應該是擴充了它的參數型態(type),參數是什麼 type 就擴充了那個 type(class),而因為是寫在某一個 class裡的,所以用 this 。

10:02:30 擴充方法必須為靜態! static  10:02:00 擴充方法 試作測試!成功,如下例示:

There is a special kind of static method which allows you to extend your existing type with new functionality without modifying the class itself.

9:47:00 當要處理外部組件中的方法時,擴充方法就很好用 This is often useful when dealing with classes provided by other assemblies.

9:49:00 Extension Methods are static methods of one class that behave like instance methods of another class.

9:50:00 The key difference between extension methods and other static methods is using a special this parameter whose type is the class to be extended.

this 就是要被擴充的 class。(不是哦!!見前)

public class Program

{

public static void Main()

{

int ten = 25.PlusFive();

Console.WriteLine(ten);

v vtest = new v();//如此,依 v 這個 class instantiate 的 instance 就有了這個(擴充)的方法,且擴充方法必為 static 但調用時卻像 instance 一樣

ForegroundColor = ConsoleColor.Red;

WriteLine( vtest.vext());

ForegroundColor = ConsoleColor.Gray;

}

}

class v//不能是 static class ,須要能建構為執行個體 instantiate object 才行!

{  // v 這個 class 不含任何 members 當然也沒有 methods 所以在它之外的 class 做一個 extension method 擴充方法



}

public static class ExtensionMethods

{

public static int PlusFive(this int input)

{

return input + 5;

}

internal static string vext(this v inp)

{

return "Yes! You've got it!!";//果然被我猜中,我理解推測地無誤!

}

}//可見擴充方法一定是跨 class 在用的,否則乾脆就寫在要被擴充的 class 裡就好。可見擴充方法通常是在不得已的情況下(無法去修改 class ,又要用其 class 作為 instance 時才做的! 也可見被擴充的 class 一定不能是 static 或不可 instantiate 才行!

//所以才會說「This is often useful when dealing with classes provided by other assemblies. 」「 using a special this parameter whose type is the class to be extended. 」所以這個 this 指定的參數是什麼 type(class) 就是擴充這個 type(class)



}



2:30:00 VBA class modules 物件類別模組

{

Property Get fFullName() As String

'Get the current file name

Dim f As String

f = Forms("歷代詞作韻律資料庫檢索表單").fFullName.ControlSource

If InStr(f, ":\") Then

fFullName = f

Else

fFullName = CurrentProject.Path & "\" & f   'CurrentProject.Path & "\@@詞學韻律資料庫設計用20170721.xlsm

End If

If Dir(fFullName) = "" Then

MsgBox "找不到來源來檔" & vbCr & vbCr & "**詞學韻律資料庫**.xlsm", vbExclamation

End

End If

End Property

VBA物件類別模組的屬性設定竟是如此容易!

原來 Access Listbox 水平捲軸是如此叫出來的:horizontal scrollbars can be added if you use 2 colums. You may add a dummy colum with a really small width (not 0). That should work fine :) http://bit.ly/2v1OeNF

http://bit.ly/2vUbdqb  http://bit.ly/2gY6cKH



}



委派和 Lambda http://bit.ly/2urtlK3



}


留言

熱門文章