C#内置函数及常用功能

C# 的内置功能主要通过 .NET 类库提供。以下是按类别分类的主要内置功能:
1. 数学计算 (System.Math)
Math.Abs(-5)        // 绝对值: 5
Math.Round(3.14)    // 四舍五入: 3
Math.Ceiling(3.14)  // 向上取整: 4
Math.Floor(3.14)    // 向下取整: 3
Math.Max(5, 10)     // 最大值: 10
Math.Min(5, 10)     // 最小值: 5
Math.Pow(2, 3)      // 幂运算: 8
Math.Sqrt(16)       // 平方根: 4
Math.Sin(Math.PI/2) // 三角函数
2. 字符串处理 (System.String)
string str = "Hello World";
// 常用方法
str.Length                    // 长度
str.ToUpper()                 // 转大写
str.ToLower()                 // 转小写
str.Substring(0, 5)           // 子字符串: "Hello"
str.Contains("World")         // 是否包含: true
str.Replace("World", "C#")    // 替换
str.Split(' ')                // 分割字符串
string.Concat("a", "b")       // 连接字符串
string.Format("{0} {1}", "Hello", "C#") // 格式化
3. 类型转换
// 显式转换
int.Parse("123")
double.Parse("3.14")
bool.Parse("true")
// 安全转换
int.TryParse("123", out int result)
Convert.ToInt32("123")
// 类型检查
int i = 10;
i.GetType()        // 获取类型
i is int           // 类型检查: true
4. 日期时间 (System.DateTime)
DateTime now = DateTime.Now;
DateTime today = DateTime.Today;
// 常用操作
now.AddDays(1)           // 加一天
now.ToString("yyyy-MM-dd") // 格式化
DateTime.Parse("2023-01-01")
now.Year                 // 年
now.Month                // 月
now.Day                  // 日
5. 数组和集合操作 
// 数组
int[] numbers = {1, 2, 3};
Array.Sort(numbers)      // 排序
Array.Reverse(numbers)   // 反转
Array.IndexOf(numbers, 2) // 查找索引
// 集合方法
List<int> list = new List<int> {1, 2, 3};
list.Add(4)              // 添加
list.Remove(2)           // 删除
list.Contains(1)         // 包含检查
6. 文件操作 (System.IO)
File.ReadAllText("file.txt")          // 读取文件
File.WriteAllText("file.txt", "内容")  // 写入文件
File.Exists("file.txt")               // 文件是否存在
Directory.GetFiles(@"C:\")            // 获取目录文件
Path.Combine("folder", "file.txt")    // 路径组合
7. 其他重要功能
// 控制台操作
Console.WriteLine("输出文本")
Console.ReadLine()        // 读取输入
Console.ReadKey()         // 读取按键
// 随机数
Random rnd = new Random();
rnd.Next(1, 100)         // 1-99之间的随机数
// 环境信息
Environment.UserName     // 当前用户名
Environment.MachineName  // 计算机名
Environment.CurrentDirectory // 当前目录
8. LINQ 查询 (System.Linq)
var numbers = new[] {1, 2, 3, 4, 5};
// 常用LINQ方法
numbers.Where(x => x > 2)     // 筛选
numbers.Select(x => x * 2)    // 投影
numbers.OrderBy(x => x)       // 排序
numbers.First()               // 第一个元素
numbers.Any(x => x > 3)       // 是否存在
numbers.Sum()                 // 求和
这些是 C# 中最常用的内置功能。实际开发中,你可以通过添加相应的 using 指令来访问这些命名空间中的功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HDHCMS(建网站+客户管理)系统

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值