namespace CSharp6._0
{
public class EmployeeInfo
{
/// <summary>
/// 只读属性只能通过构造函数赋值
/// </summary>
/// <param name="name"></param>
/// <param name="age"></param>
public EmployeeInfo(string name, int age)
{
Name = name;
Age = age;
}
public string Name { get; }
public int Age { get; }
public override string ToString() => $"{Name}+{Age}";
}
}
using System;
namespace CSharp6._0
{
public class StaticClass
{
public static void TestMethod() {
Console.WriteLine("using static");
}
public static string TestException(string name)
{
try
{
throw new Exception(name);
}
catch (Exception ex) when (ex.Message.Contains("张三"))
{
return "异常筛查";
}
}
}
}
using System;
using System.Collections.Generic;
using static CSharp6._0.StaticClass;
namespace CSharp6._0
{
class Program
{
static void Main(string[] args)
{
//只读自动属性
EmployeeInfo employeeInfo = new EmployeeInfo("张三", 29);
Console.WriteLine(employeeInfo.Name);
//using static
StaticClass.TestMethod();//以前的调用方式
TestMethod();
//Null条件与算符
EmployeeInfo employeeInfo1 = null;
string name = employeeInfo1?.Name;//当类不为null时读取Name属性
Console.WriteLine(name);
employeeInfo1 = new EmployeeInfo(null, 29);
name = employeeInfo1?.Name ?? "测试";//当类的属性为null时,赋值“测试”
Console.WriteLine(name);
//字符串内插
string str1 = "张三";
string str2 = $"{{{str1}}}属于内插字符串";
Console.WriteLine(str2);
//异常筛选器
string str = TestException("张三");
Console.WriteLine(str);
//nameof表达式
string className = nameof(StaticClass);
Console.WriteLine(className);//StaticClass
//使用索引器初始化关联集合
Dictionary<int, string> pairs = new Dictionary<int, string> {
{200, "成功" },
{500, "系统错误" }
};
Console.WriteLine(pairs[200]);
}
}
}