一、文档链接
C# 文档 - 入门、教程、参考。| Microsoft Learn
二、基础学习
1、输出语法
Console.WriteLine()
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
console
Hello World!
2、输出语句中可使用美元符号和花括号写法进行拼接
Console.WriteLine($"{}")
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
String friend = "Kcoff";
Console.WriteLine("Hello " + friend);
Console.WriteLine($"Hello {friend}");
String secondFriend = "Kendra";
Console.WriteLine($"My friend are {friend} and {secondFriend}");
}
}
}
console
Hello Kcoff
Hello Kcoff
My friend are Kcoff and Kendra
3、字符串长度查询
strName.Length
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
String friend = "Kcoff";
Console.WriteLine($"The name {friend} has {friend.Length} letters.");
}
}
}
console
The name Kcoff has 5 letters.
4、去除字符串空白符
strName.TrimStart()
、strName.TrimEnd()
、strName.Trim()
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
String greeting = " Hello World! ";
// 中括号的作用:可视化空白
Console.WriteLine($"[{greeting}]");
Console.WriteLine($"***{greeting}***");
String trimmedGreeting = greeting.TrimStart();
Console.WriteLine($"[{trimmedGreeting}]");
trimmedGreeting = greeting.TrimEnd();
Console.WriteLine($"[{trimmedGreeting}]");
trimmedGreeting = greeting.Trim();
Console.WriteLine($"[{trimmedGreeting}]");
}
}
}
console
[ Hello World! ]
*** Hello World! ***
[Hello World! ]
[ Hello World!]
[Hello World!]
5、字符串替换
strName.Replace(source, target)
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
String sayHello = "Hello World!";
Console.WriteLine(sayHello);
sayHello = sayHello.Replace("Hello", "Greetings");
Console.WriteLine(sayHello);
}
}
}
console
Hello World!
Greetings World!
6、字符串大小写转换
strName.ToUpper()
、strName.ToLower()
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
String sayHello = "Hello World!";
Console.WriteLine(sayHello.ToUpper());
Console.WriteLine(sayHello.ToLower());
}
}
}
console
HELLO WORLD!
hello world!
7、字符串是否包含什么、是否以什么为开头、是否以什么为结尾
strName.Contains(target)
、strName.StartsWith(target)
、strName.EndsWith(target)
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
String songLyrics = "You say goodbye, and I say hello";
var result = songLyrics.Contains("goodbye");
Console.WriteLine(result);
Console.WriteLine(songLyrics.Contains("greetings"));
var result2 = songLyrics.StartsWith("You");
Console.WriteLine(result2);
Console.WriteLine(songLyrics.StartsWith("goodbye"));
var result3 = songLyrics.EndsWith("hello");
Console.WriteLine(result3);
Console.WriteLine(songLyrics.EndsWith("goodbye"));
}
}
}
console
True
False
True
False
True
False
8、计算
1、加减乘除
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
int a = 18;
int b = 6;
int c = a + b;
Console.WriteLine(c);
int d = a - b;
Console.WriteLine(d);
int e = a * b;
Console.WriteLine(e);
int f = a / b;
Console.WriteLine(f);
}
}
}
console
24
12
108
3
2、计算顺序
优先计算括号里面的计算,之后先算乘除后算加减
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
int a = 5;
int b = 4;
int c = 2;
int d = a + b * c;
Console.WriteLine(d);
int e = (a + b) * c;
Console.WriteLine(e);
int f = (a + b) - 6 * c + (12 * 4) / 3 + 12;
Console.WriteLine(f);
}
}
}
console
13
18
25
3、除法只保留整数部分
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
int a = 7;
int b = 4;
int c = 3;
int d = (a + b) / c;
Console.WriteLine(d);
}
}
}
console
3
4、取余数
被除数 % 除数
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
int a = 7;
int b = 4;
int c = 3;
int d = (a + b) / c;
int e = (a + b) % c;
// 商
Console.WriteLine($"quotient: {d}");
// 余数
Console.WriteLine($"remainder: {e}");
}
}
}
console
quotient: 3
remainder: 2
9、类型(最大值、最小值及部分计算)
1、int
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
int max = int.MaxValue;
int min = int.MinValue;
Console.WriteLine($"The range of integers type is {min} to {max}");
int what = max + 3;
Console.WriteLine($"An example of overflow: {what}");
}
}
}
console
The range of integers type is -2147483648 to 2147483647
An example of overflow: -2147483646
2、double
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
double max = double.MaxValue;
double min = double.MinValue;
Console.WriteLine($"The range of double type is {min} to {max}");
}
}
}
console
The range of double type is -1.79769313486232E+308 to 1.79769313486232E+308
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
double a = 5;
double b = 4;
double c = 2;
double d = (a + b) / c;
Console.WriteLine(d);
a = 19;
b = 23;
c = 8;
double e = (a + b) / c;
Console.WriteLine(e);
double third = 1.0 / 3.0;
Console.WriteLine(third);
}
}
}
console
4.5
5.25
0.333333333333333
3、decimal
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
decimal max = decimal.MaxValue;
decimal min = decimal.MinValue;
Console.WriteLine($"The range of decimal type is {min} to {max}");
}
}
}
console
The range of decimal type is -79228162514264337593543950335 to 79228162514264337593543950335
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
double a = 1.0;
double b = 3.0;
Console.WriteLine(a / b);
decimal c = 1.0M;
decimal d = 3.0M;
Console.WriteLine(c / d);
}
}
}
console
0.333333333333333
0.3333333333333333333333333333
4、long
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
long max = long.MaxValue;
long min = long.MinValue;
Console.WriteLine($"The range of long type is {min} to {max}");
}
}
}
console
The range of long type is -9223372036854775808 to 9223372036854775807
5、short
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
short max = short.MaxValue;
short min = short.MinValue;
Console.WriteLine($"The range of short type is {min} to {max}");
}
}
}
console
The range of short type is -32768 to 32767
10、圆的面积
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
double radius = 2.50;
double area = Math.PI * radius * radius;
Console.WriteLine(area);
}
}
}
console
19.634954084936208
11、if-else 语句
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
int a = 5;
int b = 6;
bool something = a + b > 10;
if (something)
Console.WriteLine("The answer is greater then 10");
}
}
}
console
The answer is greater then 10
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
int a = 5;
int b = 3;
bool something = a + b > 10;
if (something)
{
Console.WriteLine("The answer is greater then 10");
}
else
{
Console.WriteLine("The answer is not greater then 10");
}
}
}
}
console
The answer is not greater then 10
12、&& 和 ||
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
int a = 5;
int b = 3;
int c = 4;
if ((a + b + c > 10) && (a == b))
{
Console.WriteLine("The answer is greater then 10");
Console.WriteLine("And the first number is equal to the second");
}
else
{
Console.WriteLine("The answer is not greater then 10");
Console.WriteLine("Or the first number is not equal to the second");
}
}
}
}
console
The answer is not greater then 10
Or the first number is not equal to the second
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
int a = 5;
int b = 3;
int c = 4;
if ((a + b + c > 10) || (a == b))
{
Console.WriteLine("The answer is greater then 10");
Console.WriteLine("And the first number is equal to the second");
}
else
{
Console.WriteLine("The answer is not greater then 10");
Console.WriteLine("Or the first number is not equal to the second");
}
}
}
}
console
The answer is greater then 10
And the first number is equal to the second
13、while 语句
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
int counter = 0;
while (counter < 10)
{
Console.WriteLine($"Hello World! The counter is {counter}");
counter++;
}
}
}
}
console
Hello World! The counter is 0
Hello World! The counter is 1
Hello World! The counter is 2
Hello World! The counter is 3
Hello World! The counter is 4
Hello World! The counter is 5
Hello World! The counter is 6
Hello World! The counter is 7
Hello World! The counter is 8
Hello World! The counter is 9
14、do-while 语句
和 while 语句的区别是至少会执行一次操作
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
int counter = 10;
// 至少执行一次操作
do
{
Console.WriteLine($"Hello World! The counter is {counter}");
counter++;
} while (counter < 10);
}
}
}
console
Hello World! The counter is 10
15、for 语句
1、写法
执行顺序:int index = 0 -> index < 10 -> Console.WriteLine() -> index++
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
for (int index = 0; index < 10; index++)
{
Console.WriteLine($"Hello World! The index is {index}");
}
}
}
}
console
Hello World! The index is 0
Hello World! The index is 1
Hello World! The index is 2
Hello World! The index is 3
Hello World! The index is 4
Hello World! The index is 5
Hello World! The index is 6
Hello World! The index is 7
Hello World! The index is 8
Hello World! The index is 9
2、求 1~20 中能被 3 整除的数的总和
csharp
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
int sum = 0;
for (int i = 1; i <= 20; i++)
{
if (i % 3 == 0)
{
sum = sum + i;
}
}
Console.WriteLine($"The sum is {sum}");
}
}
}
console
The sum is 63
16、Arrays、List、Collections
1、输出
foreach
、for
csharp
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var names = new List<string> { "Scott", "Kendra" };
foreach (var name in names)
{
Console.WriteLine($"Hello {name.ToUpper()}!");
}
for (int i = 0; i < names.Count; i++)
{
Console.WriteLine($"Hello {names[i].ToUpper()}!");
}
}
}
}
console
Hello SCOTT!
Hello KENDRA!
Hello SCOTT!
Hello KENDRA!
2、新增或删除
list.Add(source)
、list.Remove(source)
csharp
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var names = new List<string> { "Scott", "Kendra" };
names.Add("Maria");
names.Add("Bill");
names.Remove("Scott");
foreach (var name in names)
{
Console.WriteLine(name);
}
Console.WriteLine(names[1]);
}
}
}
console
Kendra
Maria
Bill
Maria
3、索引
list.IndexOf(target)
csharp
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var names = new List<string> { "WEIRD", "Scott", "Kendra" };
names.Add("Maria");
names.Add("Bill");
names.Remove("Scott");
foreach (var name in names)
{
Console.WriteLine(name);
}
var index = names.IndexOf("Kendra");
if (index != -1)
{
Console.WriteLine($"When an item is not found, IndexOf returns {index}");
}
else
{
Console.WriteLine($"The name {names[index]} is at index {index}");
}
}
}
}
console
WEIRD
Kendra
Maria
Bill
When an item is not found, IndexOf returns 1
4、排序
list.Sort()
csharp
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var names = new List<string> { "New Friend", "Scott", "Kendra" };
names.Add("Maria");
names.Add("Bill");
foreach (var name in names)
{
Console.WriteLine(name);
}
Console.WriteLine();
names.Sort();
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
}
console
New Friend
Scott
Kendra
Maria
Bill
Bill
Kendra
Maria
New Friend
Scott
5、斐波那契数列
csharp
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var fibonacciNumbers = new List<int> { 1, 1 };
while (fibonacciNumbers.Count < 20)
{
var previous = fibonacciNumbers[fibonacciNumbers.Count - 1];
var previous2 = fibonacciNumbers[fibonacciNumbers.Count - 2];
fibonacciNumbers.Add(previous + previous2);
}
foreach (var item in fibonacciNumbers)
{
Console.WriteLine(item);
}
}
}
}
console
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
17、面向对象
1、模拟银行创建用户并存钱
csharp
using System;
namespace ConsoleApp
{
public class BankAccount
{
public string Number { get; }
public string Owner { get; set; }
public decimal Balance { get; }
public BankAccount(string name, decimal initialBalance)
{
this.Owner = name;
this.Balance = initialBalance;
}
public void MakeDeposit(decimal amount, DateTime date, string note)
{
}
public void MakeWithdrawal(decimal amount, DateTime date, string note)
{
}
}
}
csharp
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var account = new BankAccount("Kendra", 10000);
Console.WriteLine($"Account {account.Number} was created for {account.Owner} with {account.Balance}");
}
}
}
console
Account was created for Kendra with 10000
2、模拟银行存款取款
csharp
using System;
namespace ConsoleApp
{
public class Transaction
{
public decimal Amount { get; }
public DateTime Date { get; }
public string Notes { get; }
public Transaction(decimal amount, DateTime date, string note)
{
this.Amount = amount;
this.Date = date;
this.Notes = note;
}
}
}
csharp
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
public class BankAccount
{
public string Number { get; }
public string Owner { get; set; }
public decimal Balance
{
get
{
decimal balance = 0;
foreach (var item in allTransactions)
{
balance += item.Amount;
}
return balance;
}
}
private static int accountNumberSeed = 1234567890;
private List<Transaction> allTransactions = new List<Transaction>();
public BankAccount(string name, decimal initialBalance)
{
this.Owner = name;
MakeDeposit(initialBalance, DateTime.Now, "Initial Balance");
this.Number = accountNumberSeed.ToString();
accountNumberSeed++;
}
// 存款
public void MakeDeposit(decimal amount, DateTime date, string note)
{
if (amount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(amount), "Amount of deposit must be positive");
}
var deposit = new Transaction(amount, date, note);
allTransactions.Add(deposit);
}
// 取款
public void MakeWithdrawal(decimal amount, DateTime date, string note)
{
if (amount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(amount), "Amount of deposit must be positive");
}
if (Balance - amount < 0)
{
throw new InvalidOperationException("Not sufficient funds for this withdrawal");
}
var withdrawal = new Transaction(-amount, date, note);
allTransactions.Add(withdrawal);
}
}
}
csharp
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var account = new BankAccount("Kendra", 10000);
Console.WriteLine($"Account {account.Number} was created for {account.Owner} with {account.Balance}");
account.MakeWithdrawal(120, DateTime.Now, "Hammock");
Console.WriteLine(account.Balance);
}
}
}
console
Account 1234567890 was created for Kendra with 10000
9880
3、存取款异常处理
csharp
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var account = new BankAccount("Kendra", 10000);
Console.WriteLine($"Account {account.Number} was created for {account.Owner} with {account.Balance}");
account.MakeWithdrawal(120, DateTime.Now, "Hammock");
Console.WriteLine(account.Balance);
account.MakeWithdrawal(50, DateTime.Now, "Xbox Game");
Console.WriteLine(account.Balance);
// hey this is a comment
// Test for a negative balance
try
{
account.MakeWithdrawal(75000, DateTime.Now, "Attempt to overdraw");
}
catch (InvalidOperationException e)
{
Console.WriteLine("Exception caught trying to overdraw");
Console.WriteLine(e.ToString());
}
// Test that the initial balances must be posttive
try
{
var invalidAccount = new BankAccount("invalid", -55);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine("Exception caught creating account with negative balance");
Console.WriteLine(e.ToString());
}
}
}
}
console
Account 1234567890 was created for Kendra with 10000
9880
9830
Exception caught trying to overdraw
System.InvalidOperationException: Not sufficient funds for this withdrawal
at ConsoleApp.BankAccount.MakeWithdrawal(Decimal amount, DateTime date, String note) in F:\CSharpRepository\ConsoleApp\ConsoleApp\BankAccount.cs:line 58
at ConsoleApp.Program.Main(String[] args) in F:\CSharpRepository\ConsoleApp\ConsoleApp\Program.cs:line 24
Exception caught creating account with negative balance
System.ArgumentOutOfRangeException: Amount of deposit must be positive (Parameter 'amount')
at ConsoleApp.BankAccount.MakeDeposit(Decimal amount, DateTime date, String note) in F:\CSharpRepository\ConsoleApp\ConsoleApp\BankAccount.cs:line 44
at ConsoleApp.BankAccount..ctor(String name, Decimal initialBalance) in F:\CSharpRepository\ConsoleApp\ConsoleApp\BankAccount.cs:line 32
at ConsoleApp.Program.Main(String[] args) in F:\CSharpRepository\ConsoleApp\ConsoleApp\Program.cs:line 35
4、账户交易历史记录
csharp
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp
{
public class BankAccount
{
public string Number { get; }
public string Owner { get; set; }
public decimal Balance
{
get
{
decimal balance = 0;
foreach (var item in allTransactions)
{
balance += item.Amount;
}
return balance;
}
}
private static int accountNumberSeed = 1234567890;
private List<Transaction> allTransactions = new List<Transaction>();
public BankAccount(string name, decimal initialBalance)
{
this.Owner = name;
MakeDeposit(initialBalance, DateTime.Now, "Initial Balance");
this.Number = accountNumberSeed.ToString();
accountNumberSeed++;
}
public void MakeDeposit(decimal amount, DateTime date, string note)
{
if (amount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(amount), "Amount of deposit must be positive");
}
var deposit = new Transaction(amount, date, note);
allTransactions.Add(deposit);
}
public void MakeWithdrawal(decimal amount, DateTime date, string note)
{
if (amount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(amount), "Amount of deposit must be positive");
}
if (Balance - amount < 0)
{
throw new InvalidOperationException("Not sufficient funds for this withdrawal");
}
var withdrawal = new Transaction(-amount, date, note);
allTransactions.Add(withdrawal);
}
public string GetAccountHistory()
{
var report = new StringBuilder();
// HEADER
report.AppendLine("Date\t\tAmount\tNote");
foreach (var item in allTransactions)
{
// ROWS
report.AppendLine($"{item.Date.ToShortDateString()}\t{item.Amount}\t{item.Notes}");
}
return report.ToString();
}
}
}
csharp
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var account = new BankAccount("Kendra", 10000);
Console.WriteLine($"Account {account.Number} was created for {account.Owner} with {account.Balance}");
account.MakeWithdrawal(120, DateTime.Now, "Hammock");
account.MakeWithdrawal(50, DateTime.Now, "Xbox Game");
Console.WriteLine(account.GetAccountHistory());
}
}
}
console
Account 1234567890 was created for Kendra with 10000
Date Amount Note
2023/12/12 10000 Initial Balance
2023/12/12 -120 Hammock
2023/12/12 -50 Xbox Game
三、使用软件及快捷键
1、软件
Microsoft Visual Studio Enterprise 2022 (64 位)
2、快捷键
效果 | 快捷键 |
---|---|
运行代码(非调试) | ctrl + f5 |
运行代码(调试代码) | f5 |
多行注释 | ctrl + k,ctrl + c |
取消多行注释 | ctrl + k,ctrl + u |
格式化代码(对齐代码) | ctrl + k,ctrl + d |
自动补齐代码 | Tab |
任意位置换行以及自动加花括号 | shift + enter |
复制选中行或光标所在行 | ctrl + d |
删除选中行或光标所在行 | ctrl + l(小写L) |
输入指定行进行跳转 | ctrl + g |
将选中行或光标所在行进行移动 | alt + 方向键上或下 |
自动选中光标右侧内容 | ctrl + w |
注:直接按住 ctrl 即可