DateTime dt = DateTime.NOw; // 取得現在時間
String str = dt.ToString(); // 轉成字串,例:2012/6/5 下午 04:43:57
閱讀全文...
Happy coding.
The secret to creativity is knowing how to hide your sources.— Albert Einstein
Good artists copy, great artists steal. – Pablo Picasso
2012年6月5日 星期二
2012年1月19日 星期四
2010年5月27日 星期四
C# Tutorial – 7. Control Statements Tutorial
每個程式常常在連續的步驟後,會遇到要停下來,判斷各種情況後,在繼續往下執行。底下是一些常用到的判斷語法。
Control Statements – Seelction
The if Statement
取決於給予的條件,來執行不同的程序,當條件是 true 時,將執行那區塊的程式碼。
syntax:
if () {
statements;
} else if () {
….
} else {
statements;
}
if (money > 0) {
Console.WriteLine(“時間就是金錢({0}),朋友!”, money);
} else {
Console.WriteLine(“天啊!你真窮。”);
}
當有多種情況需要判別時,就會衍生成下面的樣子
if (xx > 100) {
statements;
} else if (xx<100 && xx > 50) {
statements;
} else if (xx<50 && xx>20) {
statements;
} else {
statements;
}
The switch Statement
取決於給予的一整組邏輯的值,當符合其特定的參數,其包含的區塊成勢將會被執行。
switch 運算式的值可以為 booleans、enums、integral types和Strings。
syntax:
switch ()
{
case value1:
statements;
break;
case value2:
statements;
break;
…
default:
statements;
break;
}
int myInt;
myInt = Console.ReadLine();
// switch with integer type
switch (myInt)
{
case 1:
Console.WriteLine("Your number is {0}.", myInt);
break;
case 2:
Console.WriteLine("Your number is {0}.", myInt);
break;
case 3:
Console.WriteLine("Your number is {0}.", myInt);
break;
default: // 當都不符合上面條件時,就會執行此區塊
Console.WriteLine("Your number {0} is not between 1 and 3.", myInt);
break;
}
Control Statements – Loops
當要重複執行某些特定的動作,loops是最後達成這任務的。
The for Loop
for loop包含三個部分:起始值、條件判斷和條件增量。
syntax:
for (; ; ) {
}
ForLoop.cs
using System;
class ForLoop
{
public static void Main()
{
for (int i=0; i < 20; i++)
{
if (i == 10)
break;
if (i % 2 == 0)
continue;
Console.Write("{0} ", i);
}
Console.WriteLine();
}
}
Output:
1 3 5 7 9
說明:
1. i的起始值為0;條件式是小於20;i的增量每次加1。
2. 當i等於10的時候就會跳出for loop。
3. i被2整除時,i直接加1。
The while Loop
while loop就包含一個條件式,當條件一直成立(true)時,就是一直重複執行那段程式。
syntax:
while () {
}
WhileLoop.cs
using System;
class WhileLoop
{
public static void Main()
{
int myInt = 0;
while (myInt < 10)
{
Console.Write("{0} ", myInt);
myInt++;
}
Console.WriteLine();
}
}
The do Loop
do loop動作和while loop差不多,最明顯的差異在於 do loop最少會執行一次。
syntax:
do
{
} while ();
DoWhileLoop.cs
using System;
class DoWhileLoop
{
public static void Main()
{
int myInt = 0;
do
{
Console.Write("{0} ", myInt);
myInt++;
} while (myInt < 10);
Console.WriteLine();
}
}
總結:
Selection Control Statements讓你可以用不同的判斷式來執行不同的邏輯分支的程式。
Loop Control Statements 讓你可以輕鬆重複執行同一區塊的程式。
不同的情況選擇適當的 Control Statement 將會使程式更易於閱讀和執行工作,達到事半功倍的效用。
閱讀全文...
2010年5月18日 星期二
C# Tutorial - 6. String Tutorial
字串的操作一直是各語言的重頭戲,本文主要介紹C#常用操作字串的方法,以供有興趣的朋友參考。
閱讀全文...
C# 使用 string 來宣告字元陣列。其常值使用雙引號來高告。
string str1 = “Hello, ”;
string str2 = “C#”;
str1 += str2;
System.Console.WriteLine(str1); // outputs: Hello, C#
常使用這種方式來結合字串,但是C#的字串為物件,一旦建立後就無法改變。這樣的結果會產生一堆字串物件,會產生一堆字串物件,基於效能的考量,,這時需改用 StringBuilder class 來進行大量的字串處理。
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(“str1 “);
sb.Append(“str2 “).Append(“str3”);
string str = sb.ToString();
NOTE: 在建立字串參考時要特別注意,當建立字串參考後,修改原字串的值,此參考會指向原字串的原始物件,而不是指向新修改的物件。
string str1 = “test”;
string str2 = str1;
str1 += “123”;
System.Console.WriteLine(str2); // outputs: test
使用字串
逸出字元和大五碼的中文字常常都是字串在使用上需特別注意的地方,此時反斜線(\)會有超出常人的功用在。
@ 符號會告訴字串建構函式忽略逸出字元和分行符號。因此下列兩個字串是完全相同的:
string p1 = "\\\\My Documents\\My Files\\";
string p2 = @"\\My Documents\My Files\";
@ tips is multi-line strings in C#
string str = @”select *
from txn
where bb=2”;
ToString() 用來將數值轉換成字串。
int year = 2010;
string msg = "Happy New Year " + year.ToString();
System.Console.WriteLine(msg); // outputs "Happy New Year 2010"
Null 字串和空字串
Null string 不是 System.String Object的執行個體(instance),當你嘗試去使用 Null string 的方法時,將導致 NullReferenceException 。
string nullStr = null;
int len = nullStr.Length(); // throws NullReferenceException
空字串是 System.String Object的執行個體,包含零個字元。空字串初始化如下:
string str = “”;
常用的字串使用方法
Length() 取回字串長度。
Split() 傳回字串陣列,其中每個項目都是文字。
MSDN Example:
class TestStringSplit
{
static void Main()
{
char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string text = "one\ttwo three:four,five six seven";
System.Console.WriteLine("Original text: '{0}'", text);
string[] words = text.Split(delimiterChars);
System.Console.WriteLine("{0} words in text:", words.Length);
foreach (string s in words)
{
System.Console.WriteLine(s);
}
}
}
Output:
Original text: 'one two three:four,five six seven'
7 words in text:
one
two
three
four
five
six
seven
搜尋字串內容
string 提供許多有用的方法來搜尋字串內容。下列範例使用了 IndexOf()、LastIndexOf()、StartsWith() 和 EndsWith() 方法。
MSDN Example:
class StringSearch
{
static void Main()
{
string str = "A silly sentence used for silly purposes.";
System.Console.WriteLine("'{0}'",str);
bool test1 = str.StartsWith("a silly");
System.Console.WriteLine("starts with 'a silly'? {0}", test1);
bool test2 = str.StartsWith("a silly", System.StringComparison.OrdinalIgnoreCase);
System.Console.WriteLine("starts with 'a silly'? {0} (ignoring case)", test2);
bool test3 = str.EndsWith(".");
System.Console.WriteLine("ends with '.'? {0}", test3);
int first = str.IndexOf("silly");
int last = str.LastIndexOf("silly");
string str2 = str.Substring(first, last - first);
System.Console.WriteLine("between two 'silly' words: '{0}'", str2);
}
}
Output:
'A silly sentence used for silly purposes.'
starts with 'a silly'? False
starts with 'a silly'? True (ignore case)
ends with '.'? True
between two 'silly' words: 'silly sentence used for '
連結多個字串
連結字串有兩種方法:
1. 使用 + 運算子。優點是非常容易使用,撰寫程式碼容易;缺點是會產生好多字串,造成效能問題。
string two = "two";
string str = "one " + two + " three";
System.Console.WriteLine(str);
System.Console.WriteLine(str);
上面程式碼共產生了五個字串。
2. 使用 StringBuilder class 的 Append 方法來連結字串,不會產生 + 運算子的問題。
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(“str1 “);
sb.Append(“str2 “).Append(“str3”);
string str = sb.ToString();
System.Console.WriteLine(str);
修改字串內容
字串是「不可變動的」(Immutable),所以不可能修改字串內容。然而,字串的內容可抽取至非不可變動的表單、進行修改,然後形成新的字串執行個體。
MSDN Example:
class ModifyStrings
{
static void Main()
{
string str = "The quick brown fox jumped over the fence";
System.Console.WriteLine(str);
char[] chars = str.ToCharArray();
int animalIndex = str.IndexOf("fox");
if (animalIndex != -1)
{
chars[animalIndex++] = 'c';
chars[animalIndex++] = 'a';
chars[animalIndex] = 't';
}
string str2 = new string(chars);
System.Console.WriteLine(str2);
}
}
Output:
The quick brown fox jumped over the fence
The quick brown cat jumped over the fence
說明:
1. 使用 ToCharArray 方法將字串內容抽取至 char 型別的陣列。
2. 修改此陣列中的某些項目。
3. 使用 char 陣列建立新的字串執行個體。
閱讀全文...
2010年5月17日 星期一
C# Tutorial - 5. Array Tutorial
陣列是各語言最常用的資料結構,本文主要介紹C#操作陣列的方法,以供有興趣的朋友參考。
閱讀全文...
陣列是一種資料結構,其中會包含多個相同型別的變數。陣列是用型別宣告:
type[] arrayName;
C#陣列有下列屬性:
* 陣列是以0為起始索引,即包含 n 個元素的陣列建立索引時,會從 0 開始,一直到 n-1 為止。
* 陣列可以是一維、多維或不規則。
* 數值陣列元素的預設值會設定為零,而參考元素則設定為 null。
* 不規則陣列是指包含陣列的陣列,因此其元素為參考型別,而且會初始化為 null。
* 陣列元素可以是任何型別,包括陣列型別。
* 陣列型別是從抽象基底型別 Array 衍生的參考型別。由於此型別會實作 IEnumerable 和 IEnumerable,您可以在 C# 中的所有陣列上使用 foreach 反覆運算。
Declaring Arrays(宣告)
Example:
Single-dimensional arrays:
int[] numbers;
Multidimensional arrays:
string[,] names;
Array-of-arrays (jagged):
byte[][] scores;
Initializing Arrays(初始化)
C# array 都是 Objects,使用前都必須先初始化。
Note 如果 Array 宣告時未初始化,其元素將會被自動初始化為個型態的預設值,數值為 0,其他參考元素為NULL。
Example:
Single-Dimensional Array
int[] numbers = new int[5] {1, 2, 3, 4, 5};
string[] names = new string[3] {"Matt", "Joanne", "Robert"};
- or -
int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {"Matt", "Joanne", "Robert"};
- or -
int[] numbers = {1, 2, 3, 4, 5};
string[] names = {"Matt", "Joanne", "Robert"};
Multidimensional Array
int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} };
- or -
int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Albert"} };
- or -
int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} };
Jagged Array (Array-of-Arrays)
int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
- or -
int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
-or-
int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
Accessing Array Members(使用)
Example:
Single-Dimensional Array
int[] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
numbers[4] = 5;
Multidimensional array
int[,] numbers = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };
numbers[1, 1] = 5;
Jagged array
int[][] numbers = new int[][] { new int[] {1, 2}, new int[] {3, 4, 5}
};
設定值
numbers[0][0] = 58;
numbers[1][1] = 667;
Arrays are Objects
在 C#, arrays 實際上是個物件。 System.Array 為最基礎的類別,提供了許多有用的 methods/properties。
Example:
int[] numbers = {1, 2, 3, 4, 5};
int LengthOfNumbers = numbers.Length;
Using foreach on Arrays
利用 foreach 可以簡單且清楚的方法來逐一查看陣列中的元素。
Example:
Single-Dimensional Array
int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in numbers)
{
System.Console.WriteLine(i);
}
Multidimensional Array
int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}};
foreach(int i in numbers)
{
Console.Write("{0} ", i);
}
The output of this example is:
9 99 3 33 5 55
閱讀全文...
C# Tutorial - 4. Statements and Expression Tutorial
本文主要介紹C#最基本要件和運算式,以供有興趣的朋友參考。
閱讀全文...
Statements
Statement為C#最基本的組成,所有程式都是由Statement建構的,可以宣告區域變數、常數、呼叫方法、建立物件,或指派值給變數、屬性或欄位。
Statement通常以分號結尾。
常見的Statements
分類 | C# 關鍵字 |
Declaration statements | xx=2 |
Expression statements | area = 3.14 * (radius * radius); |
Selection statements | if、else、switch、case |
Iteration statements | do、for、foreach、in、while |
Jump statements | break、continue、default、goto、return、yield |
Exception handling statements | throw、try-catch、try-finally、try-catch-finally |
Msdn Example:
static void Main() { // Declaration statement. int counter; // Assignment statement. counter = 1; // Error! This is an expression, not an expression statement. // counter + 1; // Declaration statements with initializers are functionally // equivalent to pointA declaration statement followed by assignment statement: int[] radii = { 15, 32, 108, 74, 9 }; // Declare and initialize an array. const double pi = 3.14159; // Declare and initialize pointA constant. // foreach statement block that contains multiple statements. foreach (int radius in radii) { // Declaration statement with initializer. double circumference = pi * (2 * radius); // Expression statement (method invocation). A single-line // statement can span multiple text lines because line breaks // are treated as white space, which is ignored by the compiler. System.Console.WriteLine("Radius of circle #{0} is {1}. Circumference = {2:N2}", counter, radius, circumference); // Expression statement (postfix increment). counter++; } // End of foreach statement block } // End of Main method body.} // End of SimpleStatements class.Expression
運算式是程式碼片段,可判定為單一的值、物件、方法或命名空間。
運算式可包含常值、方法引動過程、運算子和運算元,或「簡單名稱」(Simple Name)。簡單名稱可以是變數的名稱、型別成員、方法參數、命名空間或型別。
Msdn example:
((x < 10) && ( x > 5)) || ((x > 20) && (x < 25))
System.Convert.ToInt32("35")
閱讀全文...
C# Tutorial - 3. Operators, Types, and Variables Tutorial
本文主要介紹C#的Operators、Types和Variables,以供有興趣的朋友參考。
閱讀全文...
Variables
C# 是強型別語言,因此每一個變數和物件都必須有宣告的型別。
Types
C#內建的基礎型別有:
* Boolean Type - true and false
* numeric types
- Integrals
The Size and Range of C# Integral Types
Type | Size (in bits) | Range |
sbyte | 8 | -128 to 127 |
byte | 8 | 0 to 255 |
short | 16 | -32768 to 32767 |
ushort | 16 | 0 to 65535 |
int | 32 | -2147483648 to 2147483647 |
uint | 32 | 0 to 4294967295 |
long | 64 | -9223372036854775808 to 9223372036854775807 |
ulong | 64 | 0 to 18446744073709551615 |
char | 16 | 0 to 65535 |
- Floating Point
- Decimal
The Floating Point and Decimal Types with Size, precision, and Range
Type | Size (in bits) | precision | Range |
float | 32 | 7 digits | 1.5 x 10-45 to 3.4 x 1038 |
double | 64 | 15-16 digits | 5.0 x 10-324 to 1.7 x 10308 |
decimal | 128 | 28-29 decimal places | 1.0 x 10-28 to 7.9 x 1028 |
*String - is a sequence of text characters.
字串物件是不變的,表示一旦建立就無法變更。修改字串會有新字串物件的建立,所以基於效能的考量,必須使用 StringBuilder 類別執行大量的串連或其他所需的字串管理,以後再做更詳細的介紹
C# Character Escape Sequences
Escape Sequence | Meaning |
\' | Single Quote |
\" | Double Quote |
\\ | Backslash |
\0 | Null, not the same as the C# null value |
\a | Bell |
\b | Backspace |
\f | form Feed |
\n | Newline |
\r | Carriage Return |
\t | Horizontal Tab |
\v | Vertical Tab |
Operators
在 C# 中,運算子是條件或符號,需要以一或多個運算式 (稱為運算元) 做為輸入並傳回值。
Operators with their precedence and Associativity
Category (by precedence) | Operator(s) | Associativity |
Primary | x.y f(x) a[x] x++ x-- new typeof default checked unchecked delegate | left |
Unary | + - ! ~ ++x --x (T)x | left |
Multiplicative | * / % | left |
Additive | + - | left |
Shift | << >> | left |
Relational | < > <= >= is as | left |
Equality | == != | right |
Logical AND | & | left |
Logical XOR | ^ | left |
Logical OR | | | left |
Conditional AND | && | left |
Conditional OR | || | left |
Null Coalescing | ?? | left |
Ternary | ?: | right |
Assignment | = *= /= %= += -= <<= >>= &= ^= |= => | right |
閱讀全文...
2010年5月12日 星期三
C# Tutorial - 2. Command Line Arguments Tutorial
本文主要介紹C#如何處理從Command line帶進來的變數值,以供有興趣的朋友參考。
using System;
using System.Collections.Generic;
using System.Text;
namespace CmdLineInput
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("You entered the following {0} command line arguments:", args.Length);
for (int i = 0; i < args.Length; i++) {
Console.WriteLine("{0}", args[i]);
}
}
}
}
Output:
You entered the following 4 command line arguments:
A
B
C
D
說明:
1. 不像 C 和 C++,程式名稱不會當做第一個命令列引數處理。
2. 使用 for 迴圈, 將帶入的參數逐一顯示在 console 上.
另一種方式, 使用 foreach statement
using System;
using System.Collections.Generic;
using System.Text;
namespace CmdLineArgus
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("You entered the following {0} command line arguments:", args.Length);
foreach (string s in args)
{
Console.WriteLine("{0}", s);
}
}
}
}
說明:
1. foreach 提供了一個簡單且清楚的方法來逐一查看陣列中的元素.
* 用 console mode 啟動測式應該都很OK, 但大部分都是殺雞用牛刀, 使用Visual Studio編輯器請照下面步驟:
Project -> 專案名稱的 Properties -> Debug -> Start Option -> Command line arguments
然後輸入程式啟始時想帶入的參數, 如 A B C D
閱讀全文...
using System;
using System.Collections.Generic;
using System.Text;
namespace CmdLineInput
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("You entered the following {0} command line arguments:", args.Length);
for (int i = 0; i < args.Length; i++) {
Console.WriteLine("{0}", args[i]);
}
}
}
}
Output:
You entered the following 4 command line arguments:
A
B
C
D
說明:
1. 不像 C 和 C++,程式名稱不會當做第一個命令列引數處理。
2. 使用 for 迴圈, 將帶入的參數逐一顯示在 console 上.
另一種方式, 使用 foreach statement
using System;
using System.Collections.Generic;
using System.Text;
namespace CmdLineArgus
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("You entered the following {0} command line arguments:", args.Length);
foreach (string s in args)
{
Console.WriteLine("{0}", s);
}
}
}
}
說明:
1. foreach 提供了一個簡單且清楚的方法來逐一查看陣列中的元素.
* 用 console mode 啟動測式應該都很OK, 但大部分都是殺雞用牛刀, 使用Visual Studio編輯器請照下面步驟:
Project -> 專案名稱的 Properties -> Debug -> Start Option -> Command line arguments
然後輸入程式啟始時想帶入的參數, 如 A B C D
閱讀全文...
C# Tutorial - 1. Hello World Tutorial
所有語言的第一個程式, Hello World
來點不一樣的, Hello C#, :)
using System;
using System.Collections.Generic;
using System.Text;
namespace Hello1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, C#");
}
}
}
說明:
1. Main 方法是程式的進入點,程式控制會在此開始和結束。
Main method 必須在類別或結構中宣告。它必須為靜態且不應該為 public
傳回型別可以是 void 或 int。
2. WriteLine method 屬於 System.Console class, 用來將資料顯示在 console 中.
程式碼其實可以更簡潔一點, 只是用Visual Studio產生專案時, 會加了一堆東西
閱讀全文...
來點不一樣的, Hello C#, :)
using System;
using System.Collections.Generic;
using System.Text;
namespace Hello1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, C#");
}
}
}
說明:
1. Main 方法是程式的進入點,程式控制會在此開始和結束。
Main method 必須在類別或結構中宣告。它必須為靜態且不應該為 public
傳回型別可以是 void 或 int。
2. WriteLine method 屬於 System.Console class, 用來將資料顯示在 console 中.
程式碼其實可以更簡潔一點, 只是用Visual Studio產生專案時, 會加了一堆東西
閱讀全文...
訂閱:
文章 (Atom)