张德长

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

C# 语法糖测试--未完待续

/// <summary>
/// string扩展方法,可以用字符串变量加.的形式直接调用,this是关键
/// </summary>
public static class StringExtention
{
private static Regex regex = new Regex("\\d+");
public static bool IsNumber(this string s)
{
if (string.IsNullOrEmpty(s)) return false;
return regex.IsMatch(s);
}
public static bool IsNullOrEmpty(this string s)
{
if (s == null|| s == "") return true;
return false;
}
}

void Test()
{
//?可空值类型,??空合并运算符
int? a = null;//a是可空的int类型
int? b = 100;
int? c = a ?? b;//a为null,返回b
Debug.Log(c);//输出100
string s1 = null;
string s2 = "ByeBye";
string s3 = s1 ?? s2;//s1为null,返回s2
//?判空运算符
Debug.Log(s1.Length);//报错
Debug.Log(s1?.Length);//输出null
Debug.Log($"s1?.Length:{s1?.Length}");//未输出{}内的值
//集合判空运算符?[]
List<string> petList = new List<string> { "Dog", "Cat", "Bear", "Snake" };
Debug.Log(petList?[0]);//输出Dog
petList = null;
Debug.Log(petList?[0]);//输出Null,不报错;用于判断数组集合是否为空
//扩展方法
string s = "123";
Debug.Log(s.IsNumber());//输出True
Debug.Log(s.IsNullOrEmpty());//输出False
//遍历List
List<int> list = new List<int> { 1, 2, 3, 4 };
list.ForEach(item => Debug.Log(item));
//匿名类
var user = new { Name = "Tome", Age = 18, Sex = "Male" };
//匿名方法
Action<string> p = delegate (string s) { Debug.Log(s); };
p("你好啊");
}

 

posted on   张德长  阅读(44)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示