.net 框架基础

简介: .net 框架基础

字符、字符串

1.字符

占用两个字节,16位,16bit,最小值0,最大值65535

System.Char 等同于 char,如果引用了System命名空间,那么也可以简写成Char

1.1 字段

class Program
{
   
    static void Main(string[] args)
    {
   
        Console.WriteLine(Convert.ToInt32(char.MaxValue));  //字符串表示的最大范围,Convert.ToInt32是将二进制转换成十进制
        Console.WriteLine(Convert.ToInt32(char.MinValue));  //字符串表示的最小范围,Convert.ToInt32是将二进制转换成十进制
    }
}

1.2 静态方法

char chA = 'A';
char ch1 = '1';
string str = "test string";

Console.WriteLine(chA.CompareTo('C'));          //-2 (meaning 'A' is 2 less than 'C')
Console.WriteLine(chA.Equals('A'));             //"True"
Console.WriteLine(Char.GetNumericValue(ch1));   //"1"
Console.WriteLine(Char.IsControl('\t'));        //"True"
Console.WriteLine(Char.IsDigit(ch1));           //"True"
Console.WriteLine(Char.IsLetter(','));          //"False"
Console.WriteLine(Char.IsLower('u'));           //"True"
Console.WriteLine(Char.IsNumber(ch1));          //"True"
Console.WriteLine(Char.IsPunctuation('.'));     //"True"
Console.WriteLine(Char.IsSeparator(str, 4));    //"True"
Console.WriteLine(Char.IsSymbol('+'));          //"True"
Console.WriteLine(Char.IsWhiteSpace(str, 4));   //"True"
Console.WriteLine(Char.Parse("S"));             //"S"
Console.WriteLine(Char.ToLower('M'));           //"m"
Console.WriteLine('x'.ToString());              //"x"

2. 字符串

string 等价于 System.String 。string是一个不可变字符序列。

//字符串定义
string s1 = "hello";
string s2 = @"\\hello";

Console.Write(new string('*',5));        //*****

//字符串转为字符数组
string s1 = "hello";
char[] chs = s1.ToCharArray();
foreach (var item in chs)
{
    Console.WriteLine(item);
}
Console.WriteLine(new string(chs));
//输出
h
e
l
l
o
hello

2.1 null和空字符串

  • 空字符串

空字符串是值长度为0的字符串,可以用string.Empty 字段来表示。

判断一个字符串是否长度为0,可以用string.Empty来比较或者使用长度是否为0来判断。

  • null

null是指字符串指向null,没有初始化。

判断一个字符串是否为null,可以与null进行比较,或者使用方法string.IsNullOrEmpty来判断字符串是否为null或者空字符串

string empty = "";
Console.WriteLine(string.Empty == empty);
Console.WriteLine("" == empty);
Console.WriteLine(string.IsNullOrEmpty(empty));

string? nullStr = null;
Console.WriteLine(nullStr == null);
Console.WriteLine(nullStr == "");
Console.WriteLine(string.IsNullOrEmpty(nullStr));
//输出
True
True
True
True
False
True

2.2 访问字符串中的字符

string s1 = "times";
char ch = s1[1];
Console.WriteLine(ch);
//输出
i

string实现了IEnumerable< char > ,所以可以用 foreach 遍历它的字符

string s1 = "times";
foreach (var item in s1)
{
   
    Console.Write(item+",");
}
//输出
t,i,m,e,s,

2.3 搜索字符串内的字段

string s1 = "times";
Console.WriteLine(s1.StartsWith("ti"));
Console.WriteLine(s1.EndsWith("se"));
Console.WriteLine(s1.Contains("me"));
Console.WriteLine(s1.IndexOf("se"));
//输出
True
False
True
-1

2.4 字符串的修改方法

string s1 = "helloworld";
Console.WriteLine(s1.Substring(1,4));   //ello
Console.WriteLine(s1.Substring(2));     //lloworld  截取从开始位置以后的所有
Console.WriteLine(s1.Insert(5,"="));    //hello=world
Console.WriteLine(s1.Remove(4,3));      //hellrld
Console.WriteLine(s1.PadLeft(15,'-'));  //-----helloworld
Console.WriteLine(s1.Replace('l','o')); //heoooworod

string s2 = "---times---";
Console.WriteLine(s2.TrimStart('-'));   //times---
Console.WriteLine(s2.TrimEnd('-'));     //---times
Console.WriteLine(s2.Trim('-'));        //times

string s3 = "  t imes-- - ";
Console.WriteLine(s3.Trim().Length);    //10  去掉头尾的空格,得出的字符串长度

string s4 = "How are you?";
string[] s4s = s4.Split();
foreach (var ss in s4s)
{
   
    Console.WriteLine(ss);
}
//输出
//How
//are
//you?

Console.WriteLine(string.Join(" ",s4s));    //How are you?

2.5 字符串格式初体验

string patten = "hello {0},my name is {1}.";
Console.WriteLine(string.Format(patten,"lisi","zhangsan")); //hello lisi,my name is zhangsan.

//C#6 以后可以用插值
string name = "lisi";
Console.WriteLine($"hello, {name}.");     //hello,lisi.

string he = "hello";
string ll = "hello";
Console.WriteLine(he==ll);          //True
Console.WriteLine(he.Equals(ll));   //True

2.6 字符串的顺序比较

string s1 = "hello";
string s2 = "world";
Console.WriteLine(s1.CompareTo(s2));        //-1
Console.WriteLine(s1.CompareTo("hello"));   //0
Console.WriteLine(string.Compare(s1,"Hello",true)); //0        忽略大小写比较

3. StringBuilder类

它是一个可变的字符串,属于System.Text命名空间。内部容量的初始值是16个字符,如果需要添加字符,那么自动调整它的容量,默认是int.MaxValue

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++)
{
   
    //sb.Append(i + ",");
    //替换为下面这种最好
    sb.Append(i);
    sb.Append(",");
}
Console.WriteLine(sb.ToString());               //0,1,2,3,4,5,6,7,8,9,

Console.WriteLine(sb.Insert(2, "nihao"));       //0,nihao1,2,3,4,5,6,7,8,9,
Console.WriteLine(sb.Remove(sb.Length-1,1));    //0,nihao1,2,3,4,5,6,7,8,9
Console.WriteLine(sb.Replace(',','+'));         //0+nihao1+2+3+4+5+6+7+8+9

日期和时间

System空间下有三个不可变的结构体进行事件表示:DateTime、DateTimeOffset、TimeSpan

1. TimeSpan

创建TimeSpan方法:

  • 通过构造器
  • 通过调用其中一个静态 From ... 方法
  • 通过两个 DateTime相减得到
Console.WriteLine(new TimeSpan(2,30,0));        //02:30:00
Console.WriteLine(TimeSpan.FromHours(2.5));     //02:30:00
Console.WriteLine(TimeSpan.FromHours(-2.5));    //-02:30:00

TimeSpan TheDays = TimeSpan.FromDays(10) - TimeSpan.FromSeconds(1);
Console.WriteLine(TheDays.Days);            //9
Console.WriteLine(TheDays.Hours);           //23
Console.WriteLine(TheDays.Minutes);         //23
Console.WriteLine(TheDays.Seconds);         //59
Console.WriteLine(TheDays.Milliseconds);    //0

Console.WriteLine(TheDays.TotalDays);       //9.999988425925926
Console.WriteLine(TheDays.TotalHours);      //239.99972222222223
Console.WriteLine(TheDays.TotalMinutes);    //14399.983333333334
Console.WriteLine(TheDays.TotalSeconds);    //863999
Console.WriteLine(TheDays.TotalMilliseconds);   //863999000

2. DateTime

Console.WriteLine(DateTime.Now);            //2024/5/9 10:28:49
Console.WriteLine(DateTimeOffset.Now);      //2024/5/9 10:28:49 +08:00

Console.WriteLine(DateTime.UtcNow);         //2024/5/9 2:29:40      UTC标准时间
//格式化
string localDate = $"{DateTime.Now.Year}年{DateTime.Now.Month}月{DateTime.Now.Day}日 {DateTime.Now.Hour}:{DateTime.Now.Minute}:{DateTime.Now.Second}";
Console.WriteLine(localDate);   //2024年5月9日 10:33:21

随机数Random

Random能够生成类型为byte、integer或者double的伪随机数序列

Random r1 = new Random();
Console.WriteLine(r1.Next(100) + "," + r1.Next(100));

Guid 结构体

Guid 结构体表示一个全局唯一标识符。一个生成是可以肯定为全世界唯一16字节值。

Guid d = Guid.NewGuid();
Console.WriteLine(d.ToString());     //xxxx-xxxx-xxxx-xxxx-xxxx
Guid g1 = new Guid("{xxxx-xxxx-xxxx-xxxx-xxxx}");
Guid g2 = new Guid("xxxx");
Console.WriteLine(g1 == g2);        //True

常用类

Console类

常规的Console.WriteLine和Console.ReadLine()略。

//修改前景色,也就是文字的颜色
Console.ForegroundColor = ConsoleColor.Green;
//修改文字背景
Console.BackgroundColor = ConsoleColor.Red;
//光标后移多少个位置
Console.CursorLeft += 30;
//修改控制台的输出流到文件输出流
using (System.IO.TextWriter w = System.IO.File.CreateText("e:\\output.txt"))
{
   
    Console.SetOut(w);
    Console.WriteLine(Console.ReadLine());
}

Environment 类

属于System.Environment 。它提供了以下属性

  • 文件夹和文件 CurrentDirectory、SystemDirectory、CommandLine
  • 计算机和操作系统 MachineName、ProcessorCount、OSVersion、NewLine
  • 用户登录 UserName、UserInteractive、UserDomainName
  • 诊断信息 TickCount、StackTrace、WorkingSet、Version
  • 获取环境变量 GetEnvironmentVariable、GetEnvironmentVariables和SetEnvironmentVariable
Console.WriteLine(Environment.CurrentDirectory);
Console.WriteLine(Environment.SystemDirectory);
Console.WriteLine(Environment.CommandLine);
Console.WriteLine("-------------------");
Console.WriteLine(Environment.MachineName);
Console.WriteLine(Environment.ProcessorCount);
Console.WriteLine(Environment.OSVersion);
Console.WriteLine(Environment.NewLine);        //输出一个空行
Console.WriteLine("-------------------");
Console.WriteLine(Environment.UserName);
Console.WriteLine(Environment.UserInteractive);
Console.WriteLine(Environment.UserDomainName);
Console.WriteLine("-------------------");
Console.WriteLine(Environment.TickCount);
Console.WriteLine(Environment.StackTrace);
Console.WriteLine(Environment.WorkingSet);
Console.WriteLine(Environment.Version);
目录
相关文章
|
5天前
|
Linux C# Android开发
一个开源、跨平台的.NET UI框架 - Avalonia UI
一个开源、跨平台的.NET UI框架 - Avalonia UI
|
5天前
|
机器学习/深度学习 人工智能 算法
ML.NET:一个.NET开源、免费、跨平台的机器学习框架
ML.NET:一个.NET开源、免费、跨平台的机器学习框架
|
5天前
|
消息中间件 开发框架 前端开发
YuebonCore:基于.NET8开源、免费的权限管理及快速开发框架
YuebonCore:基于.NET8开源、免费的权限管理及快速开发框架
|
15天前
|
测试技术 API 开发者
.NET单元测试框架大比拼:MSTest、xUnit与NUnit的实战较量与选择指南
【8月更文挑战第28天】单元测试是软件开发中不可或缺的一环,它能够确保代码的质量和稳定性。在.NET生态系统中,MSTest、xUnit和NUnit是最为流行的单元测试框架。本文将对这三种测试框架进行全面解析,并通过示例代码展示它们的基本用法和特点。
29 7
|
15天前
|
XML 开发框架 .NET
.NET框架:软件开发领域的瑞士军刀,如何让初学者变身代码艺术家——从基础架构到独特优势,一篇不可错过的深度解读。
【8月更文挑战第28天】.NET框架是由微软推出的统一开发平台,支持多种编程语言,简化应用程序的开发与部署。其核心组件包括公共语言运行库(CLR)和类库(FCL)。CLR负责内存管理、线程管理和异常处理等任务,确保代码稳定运行;FCL则提供了丰富的类和接口,涵盖网络、数据访问、安全性等多个领域,提高开发效率。此外,.NET框架还支持跨语言互操作,允许开发者使用C#、VB.NET等语言编写代码并无缝集成。这一框架凭借其强大的功能和广泛的社区支持,已成为软件开发领域的重要工具,适合初学者深入学习以奠定职业生涯基础。
72 1
|
4天前
|
JSON 测试技术 C#
C#/.NET/.NET Core优秀项目框架推荐榜单
C#/.NET/.NET Core优秀项目框架推荐榜单
|
28天前
|
存储 开发框架 算法
ASP.NET Core 标识(Identity)框架系列(四):闲聊 JWT 的缺点,和一些解决思路
ASP.NET Core 标识(Identity)框架系列(四):闲聊 JWT 的缺点,和一些解决思路
|
28天前
|
开发框架 JSON .NET
ASP.NET Core 标识(Identity)框架系列(三):在 ASP.NET Core Web API 项目中使用标识(Identity)框架进行身份验证
ASP.NET Core 标识(Identity)框架系列(三):在 ASP.NET Core Web API 项目中使用标识(Identity)框架进行身份验证
|
1月前
|
开发框架 JavaScript 前端开发
提升生产力:8个.NET开源且功能强大的快速开发框架
提升生产力:8个.NET开源且功能强大的快速开发框架
|
11天前
|
C# Windows 开发者
超越选择焦虑:深入解析WinForms、WPF与UWP——谁才是打造顶级.NET桌面应用的终极利器?从开发效率到视觉享受,全面解读三大框架优劣,助你精准匹配项目需求,构建完美桌面应用生态系统
【8月更文挑战第31天】.NET框架为开发者提供了多种桌面应用开发选项,包括WinForms、WPF和UWP。WinForms简单易用,适合快速开发基本应用;WPF提供强大的UI设计工具和丰富的视觉体验,支持XAML,易于实现复杂布局;UWP专为Windows 10设计,支持多设备,充分利用现代硬件特性。本文通过示例代码详细介绍这三种框架的特点,帮助读者根据项目需求做出明智选择。以下是各框架的简单示例代码,便于理解其基本用法。
45 0