c#学习笔记

这篇博客详细介绍了C#的学习笔记,从搭建环境开始,包括使用VSCode启动项目,然后深入讲解了C#的基础知识,如Console应用、数据类型、各种类型的数组、参数的使用,特别是引用参数和输出参数,以及字符串方法StringBuilder的应用。此外,还讨论了枚举、类的构造和操作,如私有属性、泛型集合List<T>、字典集合、继承以及static关键字的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 搭建环境

安装vs
安装含有插件的工具

vscode启动项目

打开vscode终端,输入dotnet,如果报错dotnet
	启动图标->属性->兼容性->设置以管理员启动->所有用户设置以管理员启动
dotnet new 创建项目
dotnet run 运行项目

vs启动项目

选择控制台应用创建项目

二 基础

1 Console
using System;

Console.Title = "标题";
Console.WriteLine("打印");
Console.ReadLine("输入");

// 注释
ctrl + k + c   
// 取消注释
ctrl + k + u

// 调试
断点 + F5 + F11
// 停止调试
shift + F5 

// 查看实现
F12

// 格式化代码
ctrl + k + d
2 数据类型
// 变量  小驼峰
// 类    大驼峰

decimal num1 = 1.0m;

// 占位符 {位置编号}
string str = string.Format("num: {0}", num1);
// 标准字符串格式化
string str = string.Format("金额: {0:c}", 10);  // ¥10.00,货币 :c,之间不能加空格
string str = string.Format("{0:d2}", 2);   // 02 不足2位用0填充,超过2位正常显示
string str = string.Format("{0:f2}", 1.234);  // 1.23 显示精度,保留两位小数,四舍五入,不足补0
string str = string.Format("{0:p0}", 0.1);   // 10%,以百分数显示

// 空字符
char c1 = '\0';

int num = 1;
Console.WriteLine(num++);   // 1,后自增
Console.WriteLine(++num);   // 3, 先自增
Console.WriteLine(num);   // 3

// 三元运算符
bool b1 = 1 > 2 ? true: false;

// 数据类型转换
// Parse转换: string转换为其他数据类型
int num1 = int.Parse("18");
float num = float.Parse("18.0");
// 任意类型转string
int num2 = 10;
string st = num2.ToString();
// 隐式转换:自动转换
byte b1 = 100;
int i2 = b1;
// 显示转换:强制转换
int i3 = 100;
byte b2 = (byte)i3;
b2 += 1;
b2 = (byte)(b2 + 1);  // 隐式转为了int想加

#region
#endregion   // vs的语法,可以折叠之间的代码

// var推断类型
var v1 = 1;
var v2 = "1";

// object 任意类型
3 数组
3.1 一维数组
// 声明: 类型[] 变量;
int[] a;
Array a;
// 初始化: new 数据类型[容量];
a = new int[2];
Array b = new int[3];

// 声明 + 初始化 + 赋值
int[] a = {1, 2};
Array b = new int[]{1, 2, 3};

// 求长度
int al = a.Length

// 读取
foreach (int each in a){};

// 查找
Array.indexOf(Array, value);   // 一纬数组查找第一个匹配值

// 清空
Array.Clear(a, 0, a.Length);
3.2 二维数组
int[,] array = new int[2,3];
array[0, 2] = 1;

// 获取行数
array.GetLength(0);
// 获取列数
array.GetLength(1);

// 读取所有元素
foreach (int item in array)
{
    // 依次读取了所有元素
}
3.3 交错数组
// 交错数组,每行数据长度可以不一致
int[][] arr;
arr = new int[2][];
arr[0] = new int[3];   // 定义第一行

int[][] a = new int[2][];
a[0] = new int[2] { 1, 3 };
a[1] = new int[3] { 1, 2, 3 };
foreach (int[] item in a)
{
    foreach (int i in item)
    {
        Console.WriteLine(i);
    }
}
3.4 参数数组
// params参数数组,对于方法内部而言就是普通数组,对于调用者而言,可以传递数组或一组数据类型相同的变量或不传参数

private static int Add(params int[] arr)
{
    int sum = 0;
    foreach(var item in arr)
    {
        sum += item;
    }
    return sum;
}

Add(1, 2, 3, 5);
Add();
4 参数
4.1 引用参数
// 引用参数 ref
private static void F1(ref int a)
{
    // 修改变量的值
    a = 2;
}

int a = 1;
F1(ref a);   // 执行后a等于2;
4.2 输出参数
// 输出参数,out,按引用传递
private static void F2(out int a)
{
    a = 2;
}

int a;
F2(out a);   // 2

// 输出参数函数内必须给输出参数赋值
// 输出参数传递前可以不赋值
// 这样函数可以返回多个结果
4.3 随机数
Random random = new Random();
int r = random.Next(1, 2);   // 左闭右开,取不到右边的值
5 字符串方法
StringBuilder
// 可变字符串
// 频繁变更时使用
StringBuilder builder = new StringBuilder();
builder.Append("aaaa");

private static void R2(string str)
 {
    string[] sl = str.Split(" ");
    StringBuilder sb = new StringBuilder();
    for(int i=sl.Length-1; i>=0; i--)
    {
        sb.Append(sl[i] + " ");  
    }
    string res = sb.ToString();  // 转为string
    res.Trim();   // 去掉前后空格
    Console.WriteLine(res);
}
6 枚举
[Flags]   // 允许多选
enum Move
{
	up = 1,
	down = 2,
	left = 4
}

Move up = Move.up;
Console.WriteLine(up);

// 选择多个枚举值
// 枚举值为2**n,使用 | 按位或 来多选
// 定义枚举时 [Flags] 特性修饰
// 判断的时候先 & 按位与 后再不为0


using System;

namespace test_1113_04
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Mj(Move.up | Move.left);    
            Mj((Move)1 | (Move)4);  
        }

        public enum Move
        {
            up = 1,
            down = 2,
            left = 4
        }

        public static void Mj(Move move)
        {
            if ((move & Move.up) != 0)
            {
                Console.WriteLine("up");
            }
            if ((move & Move.left) == Move.left)
            {
                Console.WriteLine("left");
            }   
        }
    }
}

// 字符串转枚举
(Move)Enum.Parse(typeof(Move), "left");
// 枚举转字符串
Enum.up.ToString();
7 类
7.1 私有属性操作
using System;

namespace test_1114_01
{
    public class Preson
    {   
        // 字段
        private string name;   
        private int age;

        // 属性:保护字段
        public string Name
        {
            get { return name; }
            set { name = value; }   // value表示要设置的值
        }
        
        // 自动属性
        public string Sex{get; set;}   // 包含1个隐藏字段,2个方法

        public int GetAge()
        {
            return age;
        }

        public void SetAge(int age)
        {
            this.age = age;
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Preson p = new Preson();
            p.Name = "哈哈";  // 设置数据,执行set
            Console.WriteLine(p.Name);  // 执行get
            p.SetAge(18);
            Console.WriteLine(p.GetAge());
        }

    }
}
7.2 构造函数
// 构造函数提供了创建对象的方式
// 与类同名,没有返回值,不要用void修饰
// 创建对象时自动调用,可用于初始化实例数据成员

using System;

namespace test_1114_01
{
    public class Preson
    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
		
        // 构造函数,为字段赋值, this()表示调用无参构造函数,()内传参(name),表示调用指定参数的构造函数
        public Preson(string name):this()   
        {
            this.Name = name; 
        }

        public Preson()   // 重载构造函数,无参构造函数
        {
            Console.WriteLine("创建对象");
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Preson p = new Preson();
            p.Name = "哈哈";  // 设置数据
            Console.WriteLine(p.Name);

            Preson p2 = new Preson("呵呵");
            Console.WriteLine(p2.Name);
        }
    }
}
7.3 泛型集合List
// List<类型> 变量 = new List<类型>();
List<Preson> pl = new List<preson>();
pl.Add(new Preson());  // 增加
pl.Insert(0, new Preson());  // 按位置插入
pl.RemoveAt(1);   // 按索引删除  Remove按元素删除,只删除一个
pl.Count;         // 获取元素个数

// 转数组
pl.ToArray();
// 数组转List, new的时候括号中传数组
List<Preson> il = new List<Preson>(pl.ToArray());



using System;
using System.Collections.Generic;

namespace test_1114_01
{
    public class Preson
    {...
    }
    
    internal class Program
    {
        static void Main(string[] args)
        {
            Preson p = new Preson();
            p.Name = "哈哈";  // 设置数据

            Preson p2 = new Preson("呵呵");

            List<Preson> pl = new List<Preson>();
            pl.Add(p);
            pl.Add(p2);
            pl.Add(p2);
            pl.Insert(0, new Preson("哈哈哈"));
            pl.RemoveAt(1);  // 根据索引删除
            pl.Remove(p2);   // 根据元素删除,只删除一个
            ShowList(pl);
        }

        static void ShowList(List<Preson> args)
        {
            for (int i = 0; i < args.Count; i++)  // Count获取元素个数
            {
                Console.WriteLine(args[i].Name);
            }
        }
    }
}
7.4 字典集合
// Dictionary<键类型, 值类型> 变量 = new Dictionary<键类型, 值类型>();
Dictionary<string, Preson> pd = new Dictionary<string, Preson>();
pd.Add("a1", new Preson("a1"));   // 存
Preson pa1 = pd["a1"];            // 找
Console.WriteLine(pa1.Name);
7.5 继承
// 子类: 父类
class Stur : Preson

// 声明父类指向子类,只能用父类的成员
Preson p1 = new Stur();  
// 声明子类指向父类,需要强转,但还是只能使用父类的成员,没有子类的成员
Stur s1 = (Stur)p1;
Stur s2 = p1 as Stut;  // as 如果转换失败不会抛出异常,值为null
7.6 static
// static修饰类的成员,静态成员,属于类,被所有对象共享
// 静态构造函数不能加访问级别,初始化类的静态成员数据,类加载的时候调用一次
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值