【C#】Microsoft C# 视频学习总结

一、文档链接

C# 文档 - 入门、教程、参考。| Microsoft Learn

二、基础学习

1、输出语法

Console.WriteLine()

using System;
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
			Console.WriteLine("Hello World!");
        }
    }
}
Hello World!
using System;
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 1;
            int b = 2;
            Console.WriteLine("a = {0}, b = {1}", a, b);
        }
    }
}
a = 1, b = 2

更多输出语法可以看:C# 中 Console.WriteLine 常见的几种形式及其用法差异

2、输出语句中可使用美元符号和花括号写法进行拼接

Console.WriteLine($"{}")

using System;
namespace ConsoleApp
{
    class Program
    {
        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

更多输出语法可以看:C# 中 Console.WriteLine 常见的几种形式及其用法差异

3、字符串长度查询

strName.Length

using System;
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
			String friend = "Kcoff";
            Console.WriteLine($"The name {friend} has {friend.Length} letters.");
        }
    }
}
The name Kcoff has 5 letters.

4、去除字符串空白符

strName.TrimStart()strName.TrimEnd()strName.Trim()

using System;
namespace ConsoleApp
{
    class Program
    {
        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!]

5、字符串替换

strName.Replace(source, target)

using System;
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
			String sayHello = "Hello World!";
            Console.WriteLine(sayHello);
            sayHello = sayHello.Replace("Hello", "Greetings");
            Console.WriteLine(sayHello);
        }
    }
}
Hello World!
Greetings World!

6、字符串大小写转换

strName.ToUpper()strName.ToLower()

using System;
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
			String sayHello = "Hello World!";
            Console.WriteLine(sayHello.ToUpper());
            Console.WriteLine(sayHello.ToLower());
        }
    }
}
HELLO WORLD!
hello world!

7、字符串是否包含什么、是否以什么为开头、是否以什么为结尾

strName.Contains(target)strName.StartsWith(target)strName.EndsWith(target)

using System;
namespace ConsoleApp
{
    class Program
    {
        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

8、计算

1、加减乘除

using System;
namespace ConsoleApp
{
    class Program
    {
        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

2、计算顺序

优先计算括号里面的计算,之后先算乘除后算加减

using System;
namespace ConsoleApp
{
    class Program
    {
        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

3、除法只保留整数部分

using System;
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
			int a = 7;
            int b = 4;
            int c = 3;
            int d = (a + b) / c;
            Console.WriteLine(d);
        }
    }
}
3

4、取余数

被除数 % 除数

using System;
namespace ConsoleApp
{
    class Program
    {
        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

9、类型(最大值、最小值及部分计算)

1、int

using System;
namespace ConsoleApp
{
    class Program
    {
        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

2、double

using System;
namespace ConsoleApp
{
    class Program
    {
        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 ConsoleApp
{
    class Program
    {
        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

3、decimal

using System;
namespace ConsoleApp
{
    class Program
    {
        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 ConsoleApp
{
    class Program
    {
        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

4、long

using System;
namespace ConsoleApp
{
    class Program
    {
        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

5、short

using System;
namespace ConsoleApp
{
    class Program
    {
        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

10、圆的面积

using System;
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
			double radius = 2.50;
            double area = Math.PI * radius * radius;
            Console.WriteLine(area);
        }
    }
}
19.634954084936208

11、if-else 语句

using System;
namespace ConsoleApp
{
    class Program
    {
        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 ConsoleApp
{
    class Program
    {
        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

12、&& 和 ||

using System;
namespace ConsoleApp
{
    class Program
    {
        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 ConsoleApp
{
    class Program
    {
        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

13、while 语句

using System;
namespace ConsoleApp
{
    class Program
    {
        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

14、do-while 语句

和 while 语句的区别是至少会执行一次操作

using System;
namespace ConsoleApp
{
    class Program
    {
        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

15、for 语句

1、写法

执行顺序:int index = 0 -> index < 10 -> Console.WriteLine() -> index++

using System;
namespace ConsoleApp
{
    class Program
    {
        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

2、求 1~20 中能被 3 整除的数的总和

using System;
namespace ConsoleApp
{
    class Program
    {
        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

16、Arrays、List、Collections

1、输出

foreachfor

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!

2、新增或删除

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

3、索引

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

4、排序

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

5、斐波那契数列

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

17、面向对象

1、模拟银行创建用户并存钱

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

2、模拟银行存款取款

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

3、存取款异常处理

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

4、账户交易历史记录

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

三、使用软件及快捷键

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 即可

  • 14
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值