属性
什么是自动属性
不需要定义字段 ,在编译时vb.net教程生产对应字段,相当于是微软提供的一个“语法糖”
public int Age { get; set; }
只读自动属性
使用访问修饰符c#教程修饰set
public string Name { get; private set; }
也可以只申明get访问器
public string Name { get; }
自动属性初始化
public List<string> Names { get; set; } = new List<string>();
使用表达式初始化
public override string ToString() => Name;
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName => $"{FirstName} {LastName}";
using static
用于导入单个类的静态方法
using static System.Math;
private double CalculateArea(double r) => PI * r * r;
可以使用PI来表示Math.PI
Null条件运算符
private void EmptyJudgment()
{
var result = Names.Where(x => x.Contains("12"));
var list = result?.ToList();
var list2 = list ?? new List<string>();
}
使用 ?. 替换 . 如果result为null后面的ToList不会生效,返回值list为空
??当list不为空list2=list,如果为null则将??右侧赋值给list2
字符串内嵌
public string FullName =>
"
F
i
r
s
t
N
a
m
e
L
a
s
t
N
a
m
e
"
;
字
符
串
前
添
加
"{FirstName} {LastName}"; 字符串前添加
"FirstNameLastName";字符串前添加,在{}内可以使用C#代码
异常
过滤器
private void ExceptionFilter()
{
try
{
}
catch (Exception e) when(e.Message.Contains("400"))
{
Console.WriteLine(e);
throw;
}
}
在catch后使用when关键字进行条件筛选
finally块中使用await
private async void AwaitAtException()
{
try
{
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
await Task.Delay(1000);
}
}
Nameof
private string NameOfExpression()
{
return nameof(List);
}
nameof表达式的计算结果为符号的名称,例子返回值为“List”
使用索引器为集合初始化
public Dictionary<int, string> Dictionary { get; set; } = new Dictionary<int, string>
{
[400] = "Page Not Found",
[500] = "Server Error"
};