C#6.0语法糖

时间:2022-03-08 14:15:50
 using System;
using static System.Math;//using static,仅仅引入类中的静态方法
namespace _6._0Syntax
{
class Program
{
delegate bool Predicate(string str);
static void Main(string[] args)
{
/*nameof
string a = nameof(Program.Main);
*/ /*String interpolation
var s = string.Format("{0} is so beauty{{~~~}}", "You");
Person p = new Person { Name = "senki", Age = 12 };
var s = $"{p.Name,20} is {p.Age:D3} year{{s}} old";
*/ /*NULL操作
string str = null;
int? length = str?.Length;
char? c = str?[0];
int l = str?.Length ?? 0;
List<Person> list = null;
int? b= list?[0]?.Name?.Length;
Predicate predicate = null;
if (predicate?.Invoke(str) ?? false)
{
}
*/ /*初始化时设定索引
var numbers = new Dictionary<int, string> {
[7]="liu",
[9]="zhan",
[15]="qi"
};*/ /* 异常过滤器
try
{
throw new CustomException();
}
catch (Exception e) when (IsCanCatch(e))
{
}
*/
Max(, );//通过using static,直接使用静态方法
Console.WriteLine();
Console.ReadLine();
} //表达式函数
static void Print(string str) => Console.WriteLine($"{str}"); class Person
{
public string Name { get; set; } = "senki";//自动属性初始值设定
public bool Sex { get; } = true;
public int Age { get; set; }
public string LastName => Name;//只读属性
public char this[int i]=>Name?[i]??'A';//索引 }
class CustomException : Exception
{
public override string Message
{
get
{
return "测试异常";
}
}
}
private static bool IsCanCatch(Exception e)
{
if (e is CustomException)
return true;
return false;
} struct School
{
public string Name { get; set; }
public int Age { get; }
public School(string name, int age)
{
Name = name;
Age = age;
}
//public School():this("",120)
//{ } } }
}