/// <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("你好啊");
}