C# 文档 - 入门、教程、参考。| Microsoft Learn
Console.WriteLine()
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Hello World!
Console.WriteLine($"{}")
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}");
}
}
}
Hello Kcoff
Hello Kcoff
My friend are Kcoff and Kendra
strName.Length
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
String friend = "Kcoff";
Console.WriteLine($"The name {friend} has {friend.Length} letters.");
}
}
}
The name Kcoff has 5 letters.
strName.TrimStart()
、strName.TrimEnd()
、strName.Trim()
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}]");
}
}
}
[ Hello World! ]
*** Hello World! ***
[Hello World! ]
[ Hello World!]
[Hello World!]
strName.Replace(source, target)
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);
}
}
}
Hello World!
Greetings World!
strName.ToUpper()
、strName.ToLower()
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
String sayHello = "Hello World!";
Console.WriteLine(sayHello.ToUpper());
Console.WriteLine(sayHello.ToLower());
}
}
}
HELLO WORLD!
hello world!
strName.Contains(target)
、strName.StartsWith(target)
、strName.EndsWith(target)
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"));
}
}
}
True
False
True
False
True
False
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);
}
}
}
24
12
108
3
优先计算括号里面的计算,之后先算乘除后算加减
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);
}
}
}
13
18
25
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);
}
}
}
3
被除数 % 除数
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}");
}
}
}
quotient: 3
remainder: 2
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}");
}
}
}
The range of integers type is -2147483648 to 2147483647
An example of overflow: -2147483646
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}");
}
}
}
The range of double type is -1.79769313486232E+308 to 1.79769313486232E+308
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);
}
}
}
4.5
5.25
0.333333333333333
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}");
}
}
}
The range of decimal type is -79228162514264337593543950335 to 79228162514264337593543950335
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);
}
}
}
0.333333333333333
0.3333333333333333333333333333
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}");
}
}
}
The range of long type is -9223372036854775808 to 9223372036854775807
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}");
}
}
}
The range of short type is -32768 to 32767
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
double radius = 2.50;
double area = Math.PI * radius * radius;
Console.WriteLine(area);
}
}
}
19.634954084936208
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");
}
}
}
The answer is greater then 10
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");
}
}
}
}
The answer is not greater then 10
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");
}
}
}
}
The answer is not greater then 10
Or the first number is not equal to the second
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");
}
}
}
}
The answer is greater then 10
And the first number is equal to the second
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++;
}
}
}
}
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
和 while 语句的区别是至少会执行一次操作
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);
}
}
}
Hello World! The counter is 10
执行顺序:int index = 0 -> index < 10 -> Console.WriteLine() -> index++
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}");
}
}
}
}
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
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}");
}
}
}
The sum is 63
foreach
、for
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()}!");
}
}
}
}
Hello SCOTT!
Hello KENDRA!
Hello SCOTT!
Hello KENDRA!
list.Add(source)
、list.Remove(source)
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]);
}
}
}
Kendra
Maria
Bill
Maria
list.IndexOf(target)
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}");
}
}
}
}
WEIRD
Kendra
Maria
Bill
When an item is not found, IndexOf returns 1
list.Sort()
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);
}
}
}
}
New Friend
Scott
Kendra
Maria
Bill
Bill
Kendra
Maria
New Friend
Scott
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);
}
}
}
}
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
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)
{
}
}
}
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 was created for Kendra with 10000
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;
}
}
}
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);
}
}
}
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 1234567890 was created for Kendra with 10000
9880
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());
}
}
}
}
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
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();
}
}
}
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());
}
}
}
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
Microsoft Visual Studio Enterprise 2022 (64 位)
效果 | 快捷键 |
---|---|
运行代码(非调试) | 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 即可