C # 学习笔记

C # 学习笔记

由于部分属性与Java 相同就不做笔记与记录

第一章:C# 基础

1、程序结构

一个 C# 程序主要包括以下部分:

命名空间声明(Namespace declaration)
一个 class
Class 方法
Class 属性
一个 Main 方法
语句(Statements)& 表达式(Expressions)
注释
C# 文件的后缀为 .cs。

using System;   //引包
namespace HelloWorldApplication //定义命名空间
{
   class HelloWorld   //定义类
   {
      static void Main(string[] args)   //主程序入口
      {
         /* 我的第一个 C# 程序*/
         Console.WriteLine("Hello World");  //Console 对象 打印 hello,word
         Console.ReadKey();
      }
   }
}
  • 注意: 每个程序只能有一个入口程序
    当一个方案中存在两个入口程序时报错
    多个入口程序错误
    注释掉,只留一个即可
数据类型

在 C# 中,变量分为以下几种类型:

  • 值类型(Value types)
  • 引用类型(Reference types)
  • 指针类型(Pointer types)
值类型:
  • boolean
  • byte 无符号整数77
  • char
  • decimal 28-29 有效位数
  • double
  • float
  • int
  • long
  • sbyte 有符号整数类型
  • short 有符号整数类型 短整型
  • uint 无符号整型
  • ulong 无符号长整型
  • ushort 无符号短整型
引用类型
  • 对象类型
  • 动态类型
    • 可以存储任何类型的值在动态数据类型变量中
  • 字符串类型
    字符串(String)类型 允许您给变量分配任何字符串值。字符串(String)类型是 System.String 类的别名。它是从对象(Object)类型派生的。字符串(String)类型的值可以通过两种形式进行分配:引号和 @引号。

例如:

String str = "runoob.com";

一个 @引号字符串:

  • 类似于字符串模板
@"runoob.com";

C# string 字符串的前面可以加 @(称作"逐字字符串")将转义字符(\)当作普通字符对待,比如:

string str = @"C:\Windows";

等价于:

string str = "C:\\Windows";

@ 字符串中可以任意换行,换行符及缩进空格都计算在字符串长度之内。

string str = @"<script type=""text/javascript"">
    <!--
    -->
</script>";
dynamic <variable_name> = value;
动态类型与对象类型相似,但是对象类型变量的类型检查是在编译时发生的,而动态类型变量的类型检查是在运行时发生的。
指针类型

指针类型变量存储另一种类型的内存地址。

type* identifier;
类型转换

隐式转换是不需要编写代码来指定的转换,编译器会自动进行。
显式转换需要我们手动转换
例如:

int i = 10;
byte b = (byte)i; // 显式转换,需要使用强制类型转换符号

小案例:

using System;


namespace ConsoleApp1
{

    class Rectangle {
        protected double W;
        protected double H;

        public void InitRectangle() {
            W = 5;
            H = 5;
        }

        public int GetArea() {
            return (int)(W * H); 
                     
        }

        public void Display() {
            Console.WriteLine(this.GetArea());
        }
    }
    public class Test01
    {
       


        private static void Main(string[] args)
        {
            var str = @"775959
                     dsadwqw5d
                        ";
            Rectangle rect = new Rectangle();
            rect.InitRectangle();
            rect.Display();
            Console.WriteLine(str);
        }

       
    }
}

常量

常量是固定值,程序执行期间不会改变。
常量是使用 const 关键字来定义的 。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
     class SampleClass
    {
        public int x;
        public int y;
        public const int c1 = 5;
        public const int c2 = c1 + 5;74

        public SampleClass(int p1, int p2)
        {
            x = p1;
            y = p2;
        }
    }
    internal class Test02
    {
       private static void Main(string[] args) {
            SampleClass sp = new SampleClass(1, 2);
            Console.WriteLine("sample: x {0} y {1}",sp.x,sp.y);
            Console.WriteLine("sampleL c1 {0} c2 {1}", SampleClass.c1, SampleClass.c2);
        }
    }
}

运算符

运算符是一种告诉编译器执行特定的数学或逻辑操作的符号。C# 有丰富的内置运算符,分类如下:

  • 算术运算符
  • 关系运算符
  • 逻辑运算符
  • 位运算符
  • 赋值运算符
  • 其他运算符
    • sizeof() 返回数据类型的大小。 sizeof(int),将返回 4.
    • typeof() 返回 class 的类型。 typeof(StreamReader);
    • & 返回变量的地址。 &a; 将得到变量的实际地址。
    • * 变量的指针。 *a; 将指向一个变量。
    • ? : 条件表达式 如果条件为真 ? 则为 X : 否则为 Y
    • is 判断对象是否为某一类型。 If( Ford is Car) // 检查 Ford 是否是 Car 类的一个对象。
    • as 强制转换,即使转换失败也不会抛出异常。
var str = 1234;
const int number = 0;
Console.WriteLine(sizeof(int));
Console.WriteLine(typeof(int));
Console.WriteLine(str is number);

Object obj = new StringReader("Hello");
StringReader r = obj as StringReader;

Internal 访问修饰符

Internal 访问修饰符允许一个类将其成员变量和成员函数暴露给当前程序中的其他函数和对象。换句话说,带有 internal 访问修饰符的任何成员可以被定义在该成员所定义的应用程序内的任何类或方法访问。 

继承

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ConsoleApp1
{
    internal class PersonBase
    {
        internal string Name { get; set; }
        internal int Age { get; set; }
        internal string Phone { get; set; }
        internal string Address { get; set; }

        public PersonBase(string name,int age,string Phone,string address) { 
            this.Name = name;
            this.Age = age;
            this.Phone = Phone;
            this.Address = address;
        }

        public override string? ToString()
        {
            return base.ToString();
        }
    }

    class Student : PersonBase
    {
        private string uid;
        private int score;
        private const string CLASS_NAME = "计科一班";

        
        public Student(string name, int age, string Phone, string address,string uid,int score) : base(name, age, Phone, address)
        {
            this.uid = uid;
            this.score = score;
            this.Name=name;
            this.Age = age;
            this.Phone = Phone;
            this.Address = address;
        }

        public override string? ToString()
        {
            return "" +
                "uid:" +this.uid +
                "\tname:"+this.Name;
        }
    }

    class MainP 
    {
        static void Main(string[] args) {
            Student s = new Student("张三",18,"11111","zt","123456",89);
            Student s1 = new Student("lisi",19,"11112","zt","1234567",60);
            Student s2 = new Student("nana",20,"11113","zt","12345678",50);
            Student s3 = new Student("rose",19,"11114","zt","123456789",90);

            List<Student> sList = new List<Student>() { s };
            sList.Add(s1);
            sList.Add(s2);
            sList.Add(s3);


            sList.ForEach(s => Console.WriteLine(s));
        }  
    }
}

LINQ 表达式

语言集成查询 (LINQ) 是一系列直接将查询功能集成到 C# 语言的技术统称。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class StudentEnt {
        internal int Id { get; set; }
        internal  string Uid { get; set; }
        internal string Name { get; set; }
        internal string Sex { get; set; }
        internal string ClassName { get; set; }
        internal int Score { get; set; }

        public StudentEnt(int id, string uid, string name, string sex, string className, int score)
        {
            Id = id;
            Uid = uid;
            Name = name;
            Sex = sex;
            ClassName = className;
            Score = score;
        }
        public override string ToString()  
        {  
            // 使用字符串插值或StringBuilder来构建字符串  
            // 这里使用字符串插值  
            return $"ID: {Id}, UID: {Uid}, Name: {Name}, Sex: {Sex}, Class Name: {ClassName}, Score: {Score}";  
        }  
        
    }

     class Occupation
    {
        internal int Id;
        internal string Name;
        internal int SID;

        public Occupation(int id, string name, int sId)
        {
            Id = id;
            Name = name;
            SID = sId;
        }
        public override string ToString()
        {
            return $"ID: {Id}, Name: {Name}, SID: {SID}";
        }
    }

    internal class LinQTest
    {
        static void Main(string[] args)
        {
            var sList = new List<StudentEnt>();
            var studentEnt1 = new StudentEnt(1,"2201","张三","男","计科一",76);
            var studentEnt2 = new StudentEnt(2, "2202", "李四", "男", "计科二", 82);  
            var studentEnt3 = new StudentEnt(3, "2203", "王五", "女", "软工一", 90);  
            var studentEnt4 = new StudentEnt(4, "2204", "张六", "男", "网络工程", 78);  
            var studentEnt5 = new StudentEnt(5, "2205", "孙七", "女", "计科三", 85);  
            var studentEnt6 = new StudentEnt(6, "2206", "周八", "男", "计科一", 50);  
            var studentEnt7 = new StudentEnt(7, "2207", "吴九", "女", "计科一", 92);  
            var studentEnt8 = new StudentEnt(8, "2208", "郑十", "男", "人工智能", 88);  
            var studentEnt9 = new StudentEnt(9, "2209", "钱十一", "女", "计科四", 74);  
            var studentEnt10 = new StudentEnt(10, "2210", "刘十二", "男", "计科一", 59);
            
            sList.Add(studentEnt1);
            sList.Add(studentEnt2);
            sList.Add(studentEnt3);
            sList.Add(studentEnt4);
            sList.Add(studentEnt5);
            sList.Add(studentEnt6);
            sList.Add(studentEnt7);
            sList.Add(studentEnt8);
            sList.Add(studentEnt9);
            sList.Add(studentEnt10);


            var occupation1 = new Occupation(1, "软件工程师", 1);
            //生成假数据
            var occupation2 = new Occupation(2, "Java 工程师", 3);
            var occupation3 = new Occupation(3, "数据库管理", 2);
            var occupation4 = new Occupation(4, "送外卖", 6);
            var occupation5 = new Occupation(5, "物联网", 5);

            List<Occupation> oList = new List<Occupation> { occupation1, occupation2, occupation3, occupation4, occupation5 };

            var join = oList.Join(sList,oList => oList.SID,sList => sList.Id, (O, S) =>
                new {
                    ID = S.Id,SID = O.SID,
                    Name = S.Name,
                    Sex = S.Sex,
                    ClassName = S.ClassName,
                    Score = S.Score,
                    OccupationName = O.Name
                });
            /*foreach (var item in join)  
            {  
                Console.WriteLine($"Student: {item}");  
            }*/
            // IEnumerable<StudentEnt> Query = from s in sList where s.Score < 60 select s;
            /*
             *   ID: 6, UID: 2206, Name: 周八, Sex: 男, Class Name: 计科一, Score: 50
                 ID: 10, UID: 2210, Name: 刘十二, Sex: 男, Class Name: 计科一, Score: 59
             *
             */
            // var Query = sList.Where(s => s.Score > 60).Where(s => s.ClassName.Equals("计科一"));

            /*var Query = sList.Where(s => s.ClassName.Equals("计科一")).First();
            Console.WriteLine(Query);*/

            var ents = sList.Where(s => s.Name.Contains("张"));
            
            foreach (var item in ents)
              {
                  Console.WriteLine(item);
              }     
        }
    }
}

其他部分后面有时间再补充

asp.net core

直接走前后端分离架构

先看主程序


using WebApplication1;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//依赖注入
builder.Services.AddSingleton<IStudent, StudentServiceImpl>();  //单例注入
//builder.Services.AddScoped<IStudent, StudentServiceImpl>();  //作用域注入
//builder.Services.AddTransient<IStudent, StudentServiceImpl>(); //瞬时

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();  //使用swagger 生成 api 文档
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();   //使用认证插件

app.MapControllers();   //自动导入controller

app.Run();     //开启服务

实体

namespace WebApplication1;

public class Student
{
//这里一定要用 public 不然前端会不显示数据
    public int Id { get; set; }
    public  string? Uid { get; set; }
    public string? Name { get; set; }
    public string? Sex { get; set; }
    public string? ClassName { get; set; }
    public int Score { get; set; }
    
}


namespace WebApplication1;

public class Occupation
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public int Sid { get; set; }
}

控制器

using System.Collections;
using Microsoft.AspNetCore.Mvc;
using WebApplication1;

namespace WebApplication1.Controllers;

[ApiController]
[Route("[controller]/[action]")]
public class StudentController : ControllerBase
{
    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IStudent _student;

    public StudentController(ILogger<WeatherForecastController> logger,IStudent studentService)
    {
        _logger = logger;
        _student = studentService;
    }
    
    [HttpGet]
    public List<Student> GetStudentList()
    {
        return _student.GetStudentList();;
    }
    
    [HttpGet]
    public Student GetStudentById(int id)
    {
        return _student.GetStudentById(id);
    }

    [HttpPost]
    public List<Student> AddStudent(int id,string uid,string name,string sex, string ClassName,int score)
    {
        var student = new Student { Id = id,Uid = uid,Name = name,Sex = sex ,ClassName = ClassName ,Score = score};
        return _student.AddStudent(student);
    }

    [HttpPut]
    public List<Student> UpdateStudent(int id,string uid,string name,string sex, string ClassName,int score)
    {
        var student = new Student { Id = id,Uid = uid,Name = name,Sex = sex ,ClassName = ClassName ,Score = score };
        return _student.UpdateStudent(student);
    }

    [HttpDelete]
    public List<Student> DeleteStudentById(int id)
    {
        return _student.DeleteStudentById(id);
    }

    [HttpGet]
    public Student GetStudentByStudentByName(string name)
    {
        return _student.GetStudentByStudentByName(name);
    }

    [HttpGet]
    public List<Occupation> GetOccupationList()
    {
        return _student.GetOccupationList();
    }

    [HttpGet]
    public IEnumerable GetStudentOccupations()
    {
        return _student.GetStudentOccupations();
    }

}

接口层

using System.Collections;

namespace WebApplication1;

public interface IStudent
{
   List<Student> GetStudentList();
   Student GetStudentById(int id);
   List<Student> AddStudent(Student student);
   List<Student> UpdateStudent(Student student);
   List<Student> DeleteStudentById(int id);
   Student GetStudentByStudentByName(string name);
   List<Occupation> GetOccupationList();
   IEnumerable GetStudentOccupations();
}

service 实现类

using System.Collections;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CSharp.RuntimeBinder;

namespace WebApplication1;

public class StudentServiceImpl : IStudent
{
    List<Student> students = new List<Student>();
    private List<Occupation> oList = new List<Occupation>();

    public StudentServiceImpl()
    {
        var studentEnt1 = new Student { Id = 1, Uid = "2201", Name = "张三", Sex = "男", ClassName = "计科一", Score = 76 };  
        var studentEnt2 = new Student { Id = 2, Uid = "2202", Name = "李四", Sex = "男", ClassName = "计科二", Score = 82 };  
        var studentEnt3 = new Student { Id = 3, Uid = "2203", Name = "王五", Sex = "女", ClassName = "软工一", Score = 90 };  
        var studentEnt4 = new Student { Id = 4, Uid = "2204", Name = "张三", Sex = "男", ClassName = "网络工程", Score = 78 };  
        var studentEnt5 = new Student { Id = 5, Uid = "2205", Name = "孙七", Sex = "女", ClassName = "计科三", Score = 85 };  
        var studentEnt6 = new Student { Id = 6, Uid = "2206", Name = "周八", Sex = "男", ClassName = "计科一", Score = 50 };  
        var studentEnt7 = new Student { Id = 7, Uid = "2207", Name = "吴九", Sex = "女", ClassName = "计科一", Score = 92 };  
        var studentEnt8 = new Student { Id = 8, Uid = "2208", Name = "郑十", Sex = "男", ClassName = "人工智能", Score = 88 };  
        var studentEnt9 = new Student { Id = 9, Uid = "2209", Name = "钱十一", Sex = "女", ClassName = "计科四", Score = 74 };  
        var studentEnt10 = new Student { Id = 10, Uid = "2210", Name = "刘十二", Sex = "男", ClassName = "计科一", Score = 59 };
        
        students.Add(studentEnt1);
        students.Add(studentEnt2);
        students.Add(studentEnt3);
        students.Add(studentEnt4);
        students.Add(studentEnt5);
        students.Add(studentEnt6);
        students.Add(studentEnt7);
        students.Add(studentEnt8);
        students.Add(studentEnt9);
        students.Add(studentEnt10);
        
        
        var occupation1 = new Occupation{ Id = 1, Name = "软件工程师", Sid = 1};
        //生成假数据
        var occupation2 = new Occupation { Id = 2,Name = "Java 工程师",Sid = 3 };
        var occupation3 = new Occupation { Id = 3,Name = "数据库管理",Sid = 2 };
        var occupation4 = new Occupation { Id = 4, Name = "送外卖",Sid = 6 };
        var occupation5 = new Occupation {Id = 5, Name = "物联网", Sid = 5 };

        oList.Add(occupation1);
        oList.Add(occupation2);
        oList.Add(occupation3);
        oList.Add(occupation4);
        oList.Add(occupation5);
    }

    public List<Student> GetStudentList()
    {
        return students;
    }

    public Student GetStudentById(int id)
    {
        foreach (var student in students)
        {
            if (student.Id == id)
            {
                return student;
            }
        }

        throw new RuntimeBinderException("未查询到该学生");
    }

    public List<Student> AddStudent(Student student)
    {
        students.Add(student);
        return students;
    }

    public List<Student> UpdateStudent(Student student)
    {
        foreach (var s in students)
        {
            if (s.Id == student.Id)
            {
                s.Uid = student.Uid;
                s.Name = student.Name;
                s.Sex = student.Sex;
                s.ClassName = student.ClassName;
                s.Score = student.Score;
            }
        }
       
        return students;
    }

    public List<Student> DeleteStudentById(int id)
    {
        foreach (var s in students)
        {
            if (s.Id == id)
            {
                students.Remove(s);
                return students;
            }
        }
        throw new RuntimeBinderException("未查询到该学生");
    }

    [HttpPost]
    public Student GetStudentByStudentByName(string name)
    {
        
        var enumerable = students.Where(s => s.Name.Equals(name));
        return enumerable.FirstOrDefault();
    }
    
    public List<Occupation> GetOccupationList()
    {
        return oList;
    }

    public IEnumerable GetStudentOccupations()
    {
        return oList.Join(students,oList => oList.Sid,sList => sList.Id, (O, S) =>
            new {
                ID = S.Id,SID = O.Sid,
                Name = S.Name,
                Sex = S.Sex,
                ClassName = S.ClassName,
                Score = S.Score,
                OccupationName = O.Name
            });
    }
}

因为很多内容 和Java 很想所以就不再做基础内容了,也是直接上了.net asp 的web api 部分
做了一个小demo 来上手
前端后端都已上传
地址:https://gitee.com/adore_2621/to-do-items

  • 27
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值