C# 特性(一)
1、数据转换
例如:要把字符串“111”转换为整型,之前方式
int temp;
int.TryParse("111", out temp);
新方式
int.TryParse("111", out int temp);
Console.WriteLine(temp);
object a3 = 123;
if (a3 is int a4)
{
var tm1 = 0;
tm1 += a4;
Console.WriteLine(tm1);//
}
以上语句会输出123
2、元组
无参数名称的元组
private static (int, int) Get1()
{
return (1, 3);
}
var a2 = Get1();
Console.WriteLine(a2.Item1); //使用元组时,使用Item1,Item2来对应具体的元组里的元素
具有参数名称的元组
private static (int x, int t) Get()
{
return (1, 3);
}
在使用时直接可以通过参数名称使用
var a1 = Get();
Console.WriteLine(a1.t);
(int x, int y) tmep1 = (1, 2);
var yz = (abc: 1, abc1: 3);
Console.WriteLine(yz.abc);
3、switch语句
通过switch语句进行集合分支判断
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
IEnumerable<object> enumerableList = new List<object>() { 0,new List<int>(){1,2,3},100,null }; int sum = 0; foreach (var at in enumerableList) { switch (at) { case 0: break; case IEnumerable<int> lit: foreach (var t in lit) { sum += t; } break; case int n when n > 0: break; case null: break; } }
4、枚举和对象属性遍历
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//枚举遍历 public static string ForEnum(EState state) => state switch { EState.Close => "ceshi", _ => throw new Exception("错误"), }; //相当于如下语句 public static string ForEnum1(EState state) { switch (state) { case EState.Close: return "ceshi"; default: throw new Exception("错误"); } } //属性遍历(属性模式) public static string ForProperty(User user) => user switch { { Name: "ceshi" } => "说明", //属性Name值为ceshi 返回"说明" { Age: 11 } => throw new Exception("错误"), _ => throw new Exception("错误") };
5、数字文本改进
int sixteen = 0b0001_0000;
long billionsAndBillions = 100_000_000_000;
6、泛型约束
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// unmanaged //非空约束 public class User<T> where T : unmanaged //非空约束 { public void Show(T t) { } } User<int> user1 = new User<int>(); //User<string> user2 = new User<string>();//错误,因为string可为空
7、默认接口方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public interface IPersion { void Show(); void ShowData() { Console.WriteLine("afasdfa"); } } public class CPersion : IPersion { public void Show() { Console.WriteLine("aaaa1111"); } } IPersion cPersion = new CPersion(); cPersion.Show(); cPersion.ShowData();
8、异常过滤
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public void TesetThrow() { try { //throw new Exception("abc"); throw new Exception("ttt"); } catch (Exception ex) when (ex.Message.Contains("abc")) { Console.WriteLine(ex); } catch (Exception ex) { Console.WriteLine(ex); } }