// LINQ
//架構
// from
// where
// select
// using System.Linq
int [] numbers = {0, 1, 2, 3, 4, 5, 6};
var evenNumQuery =
from num in numbers
where (num % 2 == 0)
select num;
foreach(int i in evenNumQuery)
{
Console.WriteLine("{0} is an even number", i);
}
/*--------------------------------------------------------------------------------------------------*/
using System.Linq
using System.Collections.Generic
public static void Main(string [] args)
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer("Alan", 25.60));
customers.Add(new Customer("Bill", -32.1));
customers.Add(new Customer("Carl", -12.2));
customers.Add(new Customer("David", 12.6));
var overdue =
from cust in customers
where cust.Balance < 0
//排列,並且從小排到大
orderby cust.Balance ascending
//排列,並且從大排到小
//orderby cust.Balance descending
//選擇多個屬性
select new{cust.Name, cust.Balance};
foreach(var cust in overdue)
{
Console.WriteLine("Name = {0}, Balance = {1}", cust.Name, cust.Balance)
}
}
狗狗的日誌
2019年4月3日 星期三
2019年3月31日 星期日
20190331-C#學習日誌
//枚舉Enum
enum DaysOfWeek
{
Sun, Mon, Tues, Wed, Thurs, Fri, Sat
}
// Tues後面未指定,將從前一個值累加
enum DaysOfWeek2
{
Sun = 5, Mon = 10, Tues, Wed, Thurs, Fri, Sat
}
// enum預設為 int(整數)型態, 可用以下方是將enum改為別的型態
enum DaysOfWeek3 : byte
{
Sun = 5, Mon = 10, Tues, Wed, Thurs, Fri, Sat
}
public static void Main(string [] args)
{
DaysOfWeek myDays = DayOfWeek.Mon;
Console.WriteLine((int)myDays); // 1
Console.WriteLine((DaysOfWeek)1); // Mon
}
/*--------------------------------------------------------------------------------------------------*/
// struct 結構
//不支援繼承
// class為引用類型, structs 為值類型
struct MyStruct
{
private int x, y;
private AmotherClass myclass;
private Days myDays;
public MyStruct(int a, int b, int c)
{
myClass = new AnotherClass();
myClass.number = a;
x = b;
y = c;
myDays = Days.Mon
}
public void PrintStatement()
{
Console.WriteLine("x = {0}, y = {1}, myDays = {2}", x, y, myDays);
}
enum Days {Mon, Tues, Wed}
class AnotherClass
{
public int number;
}
}
public static void Main(string [] args)
{
MyStruct example = new MyStruct(2, 3, 5);
example.PrintStatement();
}
enum DaysOfWeek
{
Sun, Mon, Tues, Wed, Thurs, Fri, Sat
}
// Tues後面未指定,將從前一個值累加
enum DaysOfWeek2
{
Sun = 5, Mon = 10, Tues, Wed, Thurs, Fri, Sat
}
// enum預設為 int(整數)型態, 可用以下方是將enum改為別的型態
enum DaysOfWeek3 : byte
{
Sun = 5, Mon = 10, Tues, Wed, Thurs, Fri, Sat
}
public static void Main(string [] args)
{
DaysOfWeek myDays = DayOfWeek.Mon;
Console.WriteLine((int)myDays); // 1
Console.WriteLine((DaysOfWeek)1); // Mon
}
/*--------------------------------------------------------------------------------------------------*/
// struct 結構
//不支援繼承
// class為引用類型, structs 為值類型
struct MyStruct
{
private int x, y;
private AmotherClass myclass;
private Days myDays;
public MyStruct(int a, int b, int c)
{
myClass = new AnotherClass();
myClass.number = a;
x = b;
y = c;
myDays = Days.Mon
}
public void PrintStatement()
{
Console.WriteLine("x = {0}, y = {1}, myDays = {2}", x, y, myDays);
}
enum Days {Mon, Tues, Wed}
class AnotherClass
{
public int number;
}
}
public static void Main(string [] args)
{
MyStruct example = new MyStruct(2, 3, 5);
example.PrintStatement();
}
2019年3月30日 星期六
20190330-C#學習日誌
// params 當不知道有多少參數
public void PrintDestinations(params string [] destinations)
{
for(int i = 0; i < destinations.Length; i++)
{
Console.WriteLine(destinations[i] + " ");
}
}
/*--------------------------------------------------------------------------------------------------*/
//繼承
//保護的(只有同個class與繼承的class可使用的)
class Member
{
//受保護的(同一個class 與 繼承class可使用的)
protected int annualFee;
private string name;
private int memberId;
private int memberSince;
public Member()
{
Console.WriteLine("Parent Constructor with no parameter");
}
public Member(string pName, int pMemberId, int pMemberSince)
{
Console.WriteLine("Parent Constructor with three parameters");
name = pName;
memberId = pMemberId;
memberSince = pMemberSince;
}
public override string ToString()
{
return "\nName: " + name + "\nMember ID: " + memberId +
"\nMember since: " + memberSince +
"\nTotal Annual Fee: " + annualFee;
}
//可被子類重新寫
public virtual void CalculateAnnualFee()
{
annualFee = 0;
}
}
//繼承父類
class NormalMember : Member
{
public NormalMember()
{
Console.WriteLine("Chind constructor with no parameter");
}
public NormalMember(string remarks, string name, int memberId, int memberSince)
:base(name, memberId, memberSince)
{
Console.WriteLine("Child constructor with 4 parameters");
Console.WriteLine("Remarks = {0}", remarks);
}
publice override void CalculateAnnualFee()
{
//從父類繼承的變數
annualFee = 100 + 12 * 30;
}
}
//主程序
publice static void Main(string [] args)
{
Member [] clubMembers = new Member[5];
clubMembers[0] = new NormalMember("Special Rate", "James", 1, 2010);
clubMembers[1] = new NormalMember("Normal Rate", "Andy", 2, 2011);
clubMembers[2] = new NormalMember("Normal Rate", "Bill", 3, 2011);
clubMembers[3] = new VIPMember("Carol", 4, 2011);
clubMembers[4] = new VIPMember("Evelyn", 5, 2011);
foreach(Member m in clubMembers)
{
m.CalculateAnnualFee();
Console.WriteLine(m);
}
}
//繼承父類
class VIPMember : Member
{
public VIPMember(string name, int memberId, int memberSince)
:base(name, memberId, memberSince)
{
Console.WriteLine("Child constructor with 3 parameters");
}
public override void CalculateAnnualFee()
{
annualFee = 1200;
}
}
/*--------------------------------------------------------------------------------------------------*/
// GetType() 和 typeof()
// GetType() 返回目標運行時的類型
// typeof() 接受一個類型名稱
public void PrintDestinations(params string [] destinations)
{
for(int i = 0; i < destinations.Length; i++)
{
Console.WriteLine(destinations[i] + " ");
}
}
/*--------------------------------------------------------------------------------------------------*/
//繼承
//保護的(只有同個class與繼承的class可使用的)
class Member
{
//受保護的(同一個class 與 繼承class可使用的)
protected int annualFee;
private string name;
private int memberId;
private int memberSince;
public Member()
{
Console.WriteLine("Parent Constructor with no parameter");
}
public Member(string pName, int pMemberId, int pMemberSince)
{
Console.WriteLine("Parent Constructor with three parameters");
name = pName;
memberId = pMemberId;
memberSince = pMemberSince;
}
public override string ToString()
{
return "\nName: " + name + "\nMember ID: " + memberId +
"\nMember since: " + memberSince +
"\nTotal Annual Fee: " + annualFee;
}
//可被子類重新寫
public virtual void CalculateAnnualFee()
{
annualFee = 0;
}
}
//繼承父類
class NormalMember : Member
{
public NormalMember()
{
Console.WriteLine("Chind constructor with no parameter");
}
public NormalMember(string remarks, string name, int memberId, int memberSince)
:base(name, memberId, memberSince)
{
Console.WriteLine("Child constructor with 4 parameters");
Console.WriteLine("Remarks = {0}", remarks);
}
publice override void CalculateAnnualFee()
{
//從父類繼承的變數
annualFee = 100 + 12 * 30;
}
}
//主程序
publice static void Main(string [] args)
{
Member [] clubMembers = new Member[5];
clubMembers[0] = new NormalMember("Special Rate", "James", 1, 2010);
clubMembers[1] = new NormalMember("Normal Rate", "Andy", 2, 2011);
clubMembers[2] = new NormalMember("Normal Rate", "Bill", 3, 2011);
clubMembers[3] = new VIPMember("Carol", 4, 2011);
clubMembers[4] = new VIPMember("Evelyn", 5, 2011);
foreach(Member m in clubMembers)
{
m.CalculateAnnualFee();
Console.WriteLine(m);
}
}
//繼承父類
class VIPMember : Member
{
public VIPMember(string name, int memberId, int memberSince)
:base(name, memberId, memberSince)
{
Console.WriteLine("Child constructor with 3 parameters");
}
public override void CalculateAnnualFee()
{
annualFee = 1200;
}
}
/*--------------------------------------------------------------------------------------------------*/
// GetType() 和 typeof()
// GetType() 返回目標運行時的類型
// typeof() 接受一個類型名稱
2019年3月26日 星期二
20190326-C#學習日誌
//聲明結構
//需與Class名稱相同
class Staff
{
public Staff(string name)
{
nameOfStaff = name;
Console.WriteLine("\n" + nameOfStaff);
Console.WriteLine("--------------------------------------------------");
}
public Staff(string firstName, string lastName)
{
nameOfStaff = firstName + " " + lastName;
Console.WriteLine("\n" + nameOfStaff);
Console.WriteLine("--------------------------------------------------"); }
}
/*--------------------------------------------------------------------------------------------------*/
public static void Main(string [] args)
{
//將Class實例化
Staff staff1 = new Staff("Peter");
//使用Class中的屬性或者方法
staff1.HoursWorked = 160;
int pay = staff1.CalculatePay(1000, 400);
Console.WriteLine("Pay = {0}", pay);
Staff staff2 = new Staff("John", "Tan")
staff2 = HoursWorked = 160;
pay = staff2.CalculatePay();
Console.WriteLine("Pay = {0}", pay);
Staff staff3 = new Staff("Carol");
staff3 = HoursWorked = -10;
pay = staff3.CalculatePay();
Console.WriteLine("Pay = {0}", pay);
}
/*--------------------------------------------------------------------------------------------------*/
//在螢幕列印出ToString的方法
Console.WriteLine(staff1);
//如果沒有複寫ToString
//列印出螢幕時只會顯示namespace 與 class名稱
/*--------------------------------------------------------------------------------------------------*/
//聲明靜態方法
public static double convertMilesToKilometers(double miles)
{
return miles * 1.60934;
}
/*--------------------------------------------------------------------------------------------------*/
//宣告方法,接受類型為Arrary 和 List
public void PrintFirstDestination(string [] destinations)
{
Console.WriteLine("This first destination is {0}. \n", destinations[0]);
}
public void PrintFirstDestination(List<string> destinations)
{
Console.WriteLine("This first destination is {0}. \n", destinations[0]);
}
//將屬性return 為 Arrary 或 List
public List<string> returnDestinations
{
get
{
return destinations;
}
}
public string [] returnDestinations
{
get
{
return destinations;
}
}
//需與Class名稱相同
class Staff
{
public Staff(string name)
{
nameOfStaff = name;
Console.WriteLine("\n" + nameOfStaff);
Console.WriteLine("--------------------------------------------------");
}
public Staff(string firstName, string lastName)
{
nameOfStaff = firstName + " " + lastName;
Console.WriteLine("\n" + nameOfStaff);
Console.WriteLine("--------------------------------------------------"); }
}
/*--------------------------------------------------------------------------------------------------*/
public static void Main(string [] args)
{
//將Class實例化
Staff staff1 = new Staff("Peter");
//使用Class中的屬性或者方法
staff1.HoursWorked = 160;
int pay = staff1.CalculatePay(1000, 400);
Console.WriteLine("Pay = {0}", pay);
Staff staff2 = new Staff("John", "Tan")
staff2 = HoursWorked = 160;
pay = staff2.CalculatePay();
Console.WriteLine("Pay = {0}", pay);
Staff staff3 = new Staff("Carol");
staff3 = HoursWorked = -10;
pay = staff3.CalculatePay();
Console.WriteLine("Pay = {0}", pay);
}
/*--------------------------------------------------------------------------------------------------*/
//在螢幕列印出ToString的方法
Console.WriteLine(staff1);
//如果沒有複寫ToString
//列印出螢幕時只會顯示namespace 與 class名稱
/*--------------------------------------------------------------------------------------------------*/
//聲明靜態方法
public static double convertMilesToKilometers(double miles)
{
return miles * 1.60934;
}
/*--------------------------------------------------------------------------------------------------*/
//宣告方法,接受類型為Arrary 和 List
public void PrintFirstDestination(string [] destinations)
{
Console.WriteLine("This first destination is {0}. \n", destinations[0]);
}
public void PrintFirstDestination(List<string> destinations)
{
Console.WriteLine("This first destination is {0}. \n", destinations[0]);
}
//將屬性return 為 Arrary 或 List
public List<string> returnDestinations
{
get
{
return destinations;
}
}
public string [] returnDestinations
{
get
{
return destinations;
}
}
2019年3月25日 星期一
20190325-C#學習日誌
// For Loop
for(int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
int [] myNumbers = {10, 20, 30, 40, 50};
for(int i = 0; i < myNumbers.Length; i++)
{
Console.WriteLine(myNumbers[i]);
}
/*--------------------------------------------------------------------------------------------------*/
// Foreach Loop
char [] message = {'H', 'e', 'l', 'l', 'o'};
foreach(char i in message)
{
Console.WriteLine(i);
}
/*--------------------------------------------------------------------------------------------------*/
// While
int counter = 5;
while(counter > 0)
{
Console.WriteLine("Counter = {0}", counter);
counter--;
}
/*--------------------------------------------------------------------------------------------------*/
// Do while
int counter = 100;
do
{
Console.WriteLine("Conter = {0}", counter);
counter++;
}
while (counter < 0);
/*--------------------------------------------------------------------------------------------------*/
// break
for(int i = 0; i < 5; i++)
{
Console.WriteLine("i = {0}", i);
if(i == 2)
break;
}
/*--------------------------------------------------------------------------------------------------*/
// continue
for(int i = 0; i < 5; i++)
{
Console.WriteLine("i = {0}", i);
if(i == 2)
continue;
Console.WriteLine("I will not be printed if i = 2.\n");
}
/*--------------------------------------------------------------------------------------------------*/
//異常處理 Exception Handing
int numerator, denominator;
Console.Write("Please enter numerator: ");
numerator = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter denominator: ");
denominator = Convert.ToInt32(Console.ReadLine());
try //嘗試
{
Console.WriteLine("The result is {0}", numerator / denominator);
}
catch(Exception e) //例外的處理方法
{
Console.WriteLine(e.Message);
}
finally //不論是否發生例外都會執行
{
Console.WriteLine("--- End of Error Handling Example ---");
}
/*--------------------------------------------------------------------------------------------------*/
//特定異常處理
catch(DivideByZeroException e) //除數等於零
{
Console.WriteLine(e.Message);
}
int numerator, denominator;
try
{
Console.Write("Please enter numerator: ");
numerator = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter denominator: ");
denominator = Convert.ToInt32(Console.ReadLine());
}
catch(FormatException e)
{
Console.WriteLine("Error: You did not enter an integer");
}
catch(DivideByZeroException)
{
Console.WriteLine(e.Message);
}
/*--------------------------------------------------------------------------------------------------*/
//聲明屬性
private string nameOfStaff;
private const int hourlyRate = 30;
private int hWorked;
public int HoursWorked
{
get
{
return hWorked;
}
set
{
if(value > 0)
{
hWorked = value;
}
else
{
hWorked = 0;
}
}
}
//如果沒有任何邏輯,可以使用以下簡短資料
public int HoursWorked {get; set;}
/*--------------------------------------------------------------------------------------------------*/
//聲明方法
public void PrintMessage()
{
Console.WriteLine("Calculating Pay...");
}
public int CalculatePay()
{
PrintMessage();
int staffPay;
staffPay = hWorked * hourlyRate;
if(hWorked > 0)
return staffPay;
else
return 0;
}
/*--------------------------------------------------------------------------------------------------*/
// C#允許不同方法使用同名(參數需不同)
public int CalculatePay()
{
PrintMessage();
int staffPay;
staffPay = hWorked * hourlyRate;
if(hWorked > 0)
return staffPay;
else
return 0;
}
publice int CalculatePay(int bonus, int allowance)
{
PrintMessage();
int staffPay;
staffPay = hWorked * hourlyRate + bonus + allowance;
if(hWorked > 0)
return staffPay;
else
return 0;
}
/*--------------------------------------------------------------------------------------------------*/
// ToString()的方法
//重寫方法 override
public override string ToString()
{
return "Name of Staff = " + nameOfStaff + " Hour Rate = " + hourlyRate +
" Hours Worked = " + hWorked;
}
for(int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
int [] myNumbers = {10, 20, 30, 40, 50};
for(int i = 0; i < myNumbers.Length; i++)
{
Console.WriteLine(myNumbers[i]);
}
/*--------------------------------------------------------------------------------------------------*/
// Foreach Loop
char [] message = {'H', 'e', 'l', 'l', 'o'};
foreach(char i in message)
{
Console.WriteLine(i);
}
/*--------------------------------------------------------------------------------------------------*/
// While
int counter = 5;
while(counter > 0)
{
Console.WriteLine("Counter = {0}", counter);
counter--;
}
/*--------------------------------------------------------------------------------------------------*/
// Do while
int counter = 100;
do
{
Console.WriteLine("Conter = {0}", counter);
counter++;
}
while (counter < 0);
/*--------------------------------------------------------------------------------------------------*/
// break
for(int i = 0; i < 5; i++)
{
Console.WriteLine("i = {0}", i);
if(i == 2)
break;
}
/*--------------------------------------------------------------------------------------------------*/
// continue
for(int i = 0; i < 5; i++)
{
Console.WriteLine("i = {0}", i);
if(i == 2)
continue;
Console.WriteLine("I will not be printed if i = 2.\n");
}
/*--------------------------------------------------------------------------------------------------*/
//異常處理 Exception Handing
int numerator, denominator;
Console.Write("Please enter numerator: ");
numerator = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter denominator: ");
denominator = Convert.ToInt32(Console.ReadLine());
try //嘗試
{
Console.WriteLine("The result is {0}", numerator / denominator);
}
catch(Exception e) //例外的處理方法
{
Console.WriteLine(e.Message);
}
finally //不論是否發生例外都會執行
{
Console.WriteLine("--- End of Error Handling Example ---");
}
/*--------------------------------------------------------------------------------------------------*/
//特定異常處理
catch(DivideByZeroException e) //除數等於零
{
Console.WriteLine(e.Message);
}
int numerator, denominator;
try
{
Console.Write("Please enter numerator: ");
numerator = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter denominator: ");
denominator = Convert.ToInt32(Console.ReadLine());
}
catch(FormatException e)
{
Console.WriteLine("Error: You did not enter an integer");
}
catch(DivideByZeroException)
{
Console.WriteLine(e.Message);
}
/*--------------------------------------------------------------------------------------------------*/
//聲明屬性
private string nameOfStaff;
private const int hourlyRate = 30;
private int hWorked;
public int HoursWorked
{
get
{
return hWorked;
}
set
{
if(value > 0)
{
hWorked = value;
}
else
{
hWorked = 0;
}
}
}
//如果沒有任何邏輯,可以使用以下簡短資料
public int HoursWorked {get; set;}
/*--------------------------------------------------------------------------------------------------*/
//聲明方法
public void PrintMessage()
{
Console.WriteLine("Calculating Pay...");
}
public int CalculatePay()
{
PrintMessage();
int staffPay;
staffPay = hWorked * hourlyRate;
if(hWorked > 0)
return staffPay;
else
return 0;
}
/*--------------------------------------------------------------------------------------------------*/
// C#允許不同方法使用同名(參數需不同)
public int CalculatePay()
{
PrintMessage();
int staffPay;
staffPay = hWorked * hourlyRate;
if(hWorked > 0)
return staffPay;
else
return 0;
}
publice int CalculatePay(int bonus, int allowance)
{
PrintMessage();
int staffPay;
staffPay = hWorked * hourlyRate + bonus + allowance;
if(hWorked > 0)
return staffPay;
else
return 0;
}
/*--------------------------------------------------------------------------------------------------*/
// ToString()的方法
//重寫方法 override
public override string ToString()
{
return "Name of Staff = " + nameOfStaff + " Hour Rate = " + hourlyRate +
" Hours Worked = " + hWorked;
}
2019年3月23日 星期六
20190324-C#學習日誌
//自動換行
Console.WriteLine("Hello ");
Console.WriteLine("How are you?");
//不會自動換行
Console.Write("Hello ");
Console.Write("How are you?");
//如果開頭加入
using static System.Console;
//將不必再輸入Console
WriteLine("Hello ");
WriteLine("How are you?");
//將變數列印到螢幕中
int userAge = 30;
Console.WriteLine(userAge);
//連接字串並列印到螢幕中
Console.WriteLine("Hello, " + "how are you?" + " I love C#.");
int results = 79;
Console.WriteLine("You scored " + results + " marks for your test.");
Console.WriteLine("You scored {0} marks for your test. {1}", results, "Congratulations!");
Console.WriteLine("You scored {0:F3} marks for yout test.", 123.45678);
Console.WriteLine("You have {0:C} dollars.", 2111);
/*--------------------------------------------------------------------------------------------------*/
//跳脫字元
//Tab
Console.WriteLine("Hello\tWorld");
//換行
Console.WriteLine("Hello\nWorld");
//顯示\
Console.WriteLine("\\");
//顯示"
Console.WriteLine("\"Hello!\"");
/*--------------------------------------------------------------------------------------------------*/
//接受用戶輸入字串
String userInput = Console.ReadLine();
Console.WriteLine(userInput);
/*--------------------------------------------------------------------------------------------------*/
//將字串轉換為數值
String userInput = Console.ReadLine();
int newUserInput = Convert.ToInt32(userInput);
newUserInput++;
Console.WriteLine(newUserInput);
/*--------------------------------------------------------------------------------------------------*/
//之前的總結
using System;
namespace HelloWorld
{
class MainClass
public static void Main(string [] args)
{
string userName = "";
int userAge = 0;
int currentYear = 0;
Console.WriteLine("Please enter your name: ");
userName = Console.ReadLine();
Console.WriteLine("Please enter your age: ");
userAge = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter current year: ");
currentYear = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Hello World! My name is {0} and I am {1} " +
"I was born in {2}.",
userName, userAge, currentYear - userAge);
}
}
}
/*--------------------------------------------------------------------------------------------------*/
// If and else
using System;
namespace HelloWorld
{
class MainClass
{
public static void Main(string [] args)
{
int userAge = 0;
Console.WriteLine("Please enter your age: ");
userAge = Convert.ToInt32(Console.ReadLine());
if( userAge < 0 || userAge > 100)
{
Console.WriteLine("Invalid Age.");
Console.WriteLine("Age must be between 0 and 100.");
}
else if(userAge < 18)
{
Console.WriteLine("Sorry, you are underage.");
}
else if(userAge < 21)
{
Console.WriteLine("You need parental consent.");
}
else
{
Console.WriteLine("Congratulations! You may sign up!");
}
}
} }
/*--------------------------------------------------------------------------------------------------*/
// Switch
using System;
namespace HelloWorld
{
class MainClass
{
public static void Main()
{
Console.WriteLine("Enter your grade:");
string userGrade = Console.ReadLine();
switch(userGrade)
{
case "A":
Console.WriteLine("Distinction");
break;
case "B":
Console.WriteLine("B Grade");
break;
case "C":
Console.WriteLine("C Grade");
break;
default:
Console.WriteLine("Fail");
break;
}
}
}
}
Console.WriteLine("Hello ");
Console.WriteLine("How are you?");
//不會自動換行
Console.Write("Hello ");
Console.Write("How are you?");
//如果開頭加入
using static System.Console;
//將不必再輸入Console
WriteLine("Hello ");
WriteLine("How are you?");
//將變數列印到螢幕中
int userAge = 30;
Console.WriteLine(userAge);
//連接字串並列印到螢幕中
Console.WriteLine("Hello, " + "how are you?" + " I love C#.");
int results = 79;
Console.WriteLine("You scored " + results + " marks for your test.");
Console.WriteLine("You scored {0} marks for your test. {1}", results, "Congratulations!");
Console.WriteLine("You scored {0:F3} marks for yout test.", 123.45678);
Console.WriteLine("You have {0:C} dollars.", 2111);
/*--------------------------------------------------------------------------------------------------*/
//跳脫字元
//Tab
Console.WriteLine("Hello\tWorld");
//換行
Console.WriteLine("Hello\nWorld");
//顯示\
Console.WriteLine("\\");
//顯示"
Console.WriteLine("\"Hello!\"");
/*--------------------------------------------------------------------------------------------------*/
//接受用戶輸入字串
String userInput = Console.ReadLine();
Console.WriteLine(userInput);
/*--------------------------------------------------------------------------------------------------*/
//將字串轉換為數值
String userInput = Console.ReadLine();
int newUserInput = Convert.ToInt32(userInput);
newUserInput++;
Console.WriteLine(newUserInput);
/*--------------------------------------------------------------------------------------------------*/
//之前的總結
using System;
namespace HelloWorld
{
class MainClass
public static void Main(string [] args)
{
string userName = "";
int userAge = 0;
int currentYear = 0;
Console.WriteLine("Please enter your name: ");
userName = Console.ReadLine();
Console.WriteLine("Please enter your age: ");
userAge = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter current year: ");
currentYear = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Hello World! My name is {0} and I am {1} " +
"I was born in {2}.",
userName, userAge, currentYear - userAge);
}
}
}
/*--------------------------------------------------------------------------------------------------*/
// If and else
using System;
namespace HelloWorld
{
class MainClass
{
public static void Main(string [] args)
{
int userAge = 0;
Console.WriteLine("Please enter your age: ");
userAge = Convert.ToInt32(Console.ReadLine());
if( userAge < 0 || userAge > 100)
{
Console.WriteLine("Invalid Age.");
Console.WriteLine("Age must be between 0 and 100.");
}
else if(userAge < 18)
{
Console.WriteLine("Sorry, you are underage.");
}
else if(userAge < 21)
{
Console.WriteLine("You need parental consent.");
}
else
{
Console.WriteLine("Congratulations! You may sign up!");
}
}
} }
/*--------------------------------------------------------------------------------------------------*/
// Switch
using System;
namespace HelloWorld
{
class MainClass
{
public static void Main()
{
Console.WriteLine("Enter your grade:");
string userGrade = Console.ReadLine();
switch(userGrade)
{
case "A":
Console.WriteLine("Distinction");
break;
case "B":
Console.WriteLine("B Grade");
break;
case "C":
Console.WriteLine("C Grade");
break;
default:
Console.WriteLine("Fail");
break;
}
}
}
}
2019年3月22日 星期五
20190322-C#學習日誌
using System; //使用System的命名空間
/*--------------------------------------------------------------------------------------------------*/
namespace First
{
class MyClass
{
}
}
namespace Second
{
class MyClass
{
}
}
/*--------------------------------------------------------------------------------------------------*/
public static void Main(string[] args) //主程序
{
}
/*--------------------------------------------------------------------------------------------------*/
//變數(Variable),儲存數據的名稱
int userAge; //宣告整數
byte userAge; //宣告位元組
float pi = 3.142f; //宣告32位元浮點值
double pi = 3.142; //宣告64位元的浮點值
decimal pi = 3.142m; //宣告較高精準度的浮點
char c = 'A'; 宣告字元
bool b = true; //宣告布林值 true 或者 false
/*--------------------------------------------------------------------------------------------------*/
//Camel Casing
string thisIsAVariableName; // 駝峰式大小寫
//underscores to separate words
string this_is_a_variable_name; //將不同單字用下底線隔開
/*--------------------------------------------------------------------------------------------------*/
//初始化變數
byte = userAge = 20;
int numberOfEmployees = 510;
double numberOfHours = 5120;
float hourlyRate = 60.0f;
decimal income = 25399.65m;
char grade = '#';
bool isLoggedIn = true;
byte level = 2, userExperience = 5;
byte year;
year = 20;
/*--------------------------------------------------------------------------------------------------*/
int x = 5; //一個等於是將等號右邊的值複製給等號左邊
int y = 10;
x = y; //將 y 的值複製到 x
Console.WriteLine(x); //顯示 10
/*--------------------------------------------------------------------------------------------------*/
//基本的運算符號
int x = 7, y = 2;
Console.WriteLine( x + y ); // 9
Console.WriteLine( x - y ); // 5
Console.WriteLine( x * y ); // 14
Console.WriteLine( x / y ); // 3
Console.WriteLine( x % y ); // 1
double x = 7;
int y = 2;
Console.WriteLine( x / y ); // 3.5
/*--------------------------------------------------------------------------------------------------*/
int x = 10;
x = x + 2; // 12
x += 2;
x -= 2;
x++; //先賦值在運算
++x; //先運算在賦值
/*--------------------------------------------------------------------------------------------------*/
//類型的轉換
int x = (int)20.9;
float num1 = (float)20.9;
decimal num2 = (decimal)20.9;
/*--------------------------------------------------------------------------------------------------*/
//數組(Arrary)
int [] userAge = {21, 22, 23, 24, 25};
int [] userAge2;
userAge2 = new[] {21, 22, 23, 24, 25};
int [] userAge3 = new int[5]; // {0, 0, 0, 0, 0}
//index
userAge3[0] = 31; // {31, 0, 0, 0, 0}
userAge3[2] = userAge3[2] + 20; // {31, 0, 20, 0, 0}
/*--------------------------------------------------------------------------------------------------*/
int [] userAge = {22, 21, 23, 18, 25};
Console.WriteLine(userAge.Length); //取得數組內有多少筆資料
Array.Sort(userAge); //自動排序數組 {18, 21, 22, 23, 25}
//IndexOf
int [] numbers = {10, 30, 44, 21, 51, 21, 61, 24, 14};
int ans = Array.IndexOf(numbers, 21);
// 3, 尋找是否有此筆資料, 並返回Index, 如果找不到為-1
/*--------------------------------------------------------------------------------------------------*/
//字串
string message = "Hello World";
string message2 = "Hello World, " + " my name is Kent";
int ans = message.Length; //取得字串裡面有多少字元
Console.WriteLine(message.Substring(2)); // "llo World"
Console.WriteLine(message.Substring(2, 5)); // "llo W"
// Substring(2, 5) 起始位置, 字元的長度
/*--------------------------------------------------------------------------------------------------*/
string FirstString = "This is John";
string SecondString = "Hello";
// Equals 比較字符串是否相同
FirstString.Equals("This is John"); // true
FirstString.Equals(SecondString); // false
/*--------------------------------------------------------------------------------------------------*/
//將字串分開
char [] separator = { ' , ' , ' ; ' };
string fruits = "Apple, Banana; Dureian, , Mango";
string [] substrings = fruits.Split(separator);
Console, WriteLine(substrings);
/*--------------------------------------------------------------------------------------------------*/
//列表(Lists)
List<int> userAgeList = new List<int>();
List<int> userAgeList = new List<int>{11, 21, 31, 41};
//Add, 將資料加入List的最後
userAgeList.Add(51);
userAgeList.Add(61);
//Insert, 將資料加入指定的Index
userAgeList.Insert(2, 51);
//Remove, 將第一次找到的指定資料移除
userAgeList.Remove(51);
//RemoveAt, 將指定的Index移除
userAgeList.Remove(2);
//Contains, 檢查資料是否在List裡,並回傳布林值
userAgeList.Contains(51);
//Clear, 將List裡的資料全部清除
userAgeList.Clear();
/*--------------------------------------------------------------------------------------------------*/
// value type
int myNumber = 5;
//reference
string message = "Hello";
/*--------------------------------------------------------------------------------------------------*/
namespace First
{
class MyClass
{
}
}
namespace Second
{
class MyClass
{
}
}
/*--------------------------------------------------------------------------------------------------*/
public static void Main(string[] args) //主程序
{
}
/*--------------------------------------------------------------------------------------------------*/
//變數(Variable),儲存數據的名稱
int userAge; //宣告整數
byte userAge; //宣告位元組
float pi = 3.142f; //宣告32位元浮點值
double pi = 3.142; //宣告64位元的浮點值
decimal pi = 3.142m; //宣告較高精準度的浮點
char c = 'A'; 宣告字元
bool b = true; //宣告布林值 true 或者 false
/*--------------------------------------------------------------------------------------------------*/
//Camel Casing
string thisIsAVariableName; // 駝峰式大小寫
//underscores to separate words
string this_is_a_variable_name; //將不同單字用下底線隔開
/*--------------------------------------------------------------------------------------------------*/
//初始化變數
byte = userAge = 20;
int numberOfEmployees = 510;
double numberOfHours = 5120;
float hourlyRate = 60.0f;
decimal income = 25399.65m;
char grade = '#';
bool isLoggedIn = true;
byte level = 2, userExperience = 5;
byte year;
year = 20;
/*--------------------------------------------------------------------------------------------------*/
int x = 5; //一個等於是將等號右邊的值複製給等號左邊
int y = 10;
x = y; //將 y 的值複製到 x
Console.WriteLine(x); //顯示 10
/*--------------------------------------------------------------------------------------------------*/
//基本的運算符號
int x = 7, y = 2;
Console.WriteLine( x + y ); // 9
Console.WriteLine( x - y ); // 5
Console.WriteLine( x * y ); // 14
Console.WriteLine( x / y ); // 3
Console.WriteLine( x % y ); // 1
double x = 7;
int y = 2;
Console.WriteLine( x / y ); // 3.5
/*--------------------------------------------------------------------------------------------------*/
int x = 10;
x = x + 2; // 12
x += 2;
x -= 2;
x++; //先賦值在運算
++x; //先運算在賦值
/*--------------------------------------------------------------------------------------------------*/
//類型的轉換
int x = (int)20.9;
float num1 = (float)20.9;
decimal num2 = (decimal)20.9;
/*--------------------------------------------------------------------------------------------------*/
//數組(Arrary)
int [] userAge = {21, 22, 23, 24, 25};
int [] userAge2;
userAge2 = new[] {21, 22, 23, 24, 25};
int [] userAge3 = new int[5]; // {0, 0, 0, 0, 0}
//index
userAge3[0] = 31; // {31, 0, 0, 0, 0}
userAge3[2] = userAge3[2] + 20; // {31, 0, 20, 0, 0}
/*--------------------------------------------------------------------------------------------------*/
int [] userAge = {22, 21, 23, 18, 25};
Console.WriteLine(userAge.Length); //取得數組內有多少筆資料
Array.Sort(userAge); //自動排序數組 {18, 21, 22, 23, 25}
//IndexOf
int [] numbers = {10, 30, 44, 21, 51, 21, 61, 24, 14};
int ans = Array.IndexOf(numbers, 21);
// 3, 尋找是否有此筆資料, 並返回Index, 如果找不到為-1
/*--------------------------------------------------------------------------------------------------*/
//字串
string message = "Hello World";
string message2 = "Hello World, " + " my name is Kent";
int ans = message.Length; //取得字串裡面有多少字元
Console.WriteLine(message.Substring(2)); // "llo World"
Console.WriteLine(message.Substring(2, 5)); // "llo W"
// Substring(2, 5) 起始位置, 字元的長度
/*--------------------------------------------------------------------------------------------------*/
string FirstString = "This is John";
string SecondString = "Hello";
// Equals 比較字符串是否相同
FirstString.Equals("This is John"); // true
FirstString.Equals(SecondString); // false
/*--------------------------------------------------------------------------------------------------*/
//將字串分開
char [] separator = { ' , ' , ' ; ' };
string fruits = "Apple, Banana; Dureian, , Mango";
string [] substrings = fruits.Split(separator);
Console, WriteLine(substrings);
/*--------------------------------------------------------------------------------------------------*/
//列表(Lists)
List<int> userAgeList = new List<int>();
List<int> userAgeList = new List<int>{11, 21, 31, 41};
//Add, 將資料加入List的最後
userAgeList.Add(51);
userAgeList.Add(61);
//Insert, 將資料加入指定的Index
userAgeList.Insert(2, 51);
//Remove, 將第一次找到的指定資料移除
userAgeList.Remove(51);
//RemoveAt, 將指定的Index移除
userAgeList.Remove(2);
//Contains, 檢查資料是否在List裡,並回傳布林值
userAgeList.Contains(51);
//Clear, 將List裡的資料全部清除
userAgeList.Clear();
/*--------------------------------------------------------------------------------------------------*/
// value type
int myNumber = 5;
//reference
string message = "Hello";
訂閱:
文章 (Atom)