文章目录
  1. 1. 设置只读属性
  2. 2. 属性初始化表达式
  3. 3. Expression-bodied 函数成员
  4. 4. using static
  5. 5. Null 条件运算符
  6. 6. 字符串内插
  • 设置只读属性

  • 语法如下

1
2
3
//设置只读的属性
public string FirstName { get; }
public string LastName { get; }
  • 只读属性只能在构造函数中设置
1
2
3
4
5
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}

属性初始化表达式

  • 属性可以设置初始值

    1
    public string FirstName { get; } = "";

Expression-bodied 函数成员

  • expression-bodied 成员适用于方法和只读属性
1
2
3
4
//方法
public override string ToString() => $"{FirstName},{LastName}";
//只读属性
public string FullName => $"{FirstName},{LastName}";

using static

比如我们输出一个Hello World的时候

1
Console.WriteLine("hello world");

有了using static

我们可以

1
2
3
4
5
6
7
8
9
10
11
12
using System;
using static System.Console;
namespace test
{
public class Program
{
static void Main(string[] args)
{
WriteLine("hello world");
}
}
}

貌似没鸡毛暖用,就是看起来清爽一丢丢

Null 条件运算符

  • Null 条件运算符使 null 检查更轻松、更流畅
    1
    2
    Person p =null;
    var R = p?.FirstName;//R=null

当p为null的时候返回null,当p不为null的时候返回FirstName,还可以用在方法的调用上,

1
**this.SomethingHappened?.Invoke( this, eventArgs);**

  • 分配默认值
1
2
Person p = null;
var R = p?.FirstName ?? "Unspecified";

当p为null的时候返回后边字符串,不为空的时候返回FirstName **

字符串内插

使用 $ 作为字符串的开头,并使用 {} 之间的表达式代替序号:

1
2
public string GetGradePointPercentage() =>
$"Name: {LastName}, {FirstName}. G.P.A: {Grades.Average():F2}";
文章目录
  1. 1. 设置只读属性
  2. 2. 属性初始化表达式
  3. 3. Expression-bodied 函数成员
  4. 4. using static
  5. 5. Null 条件运算符
  6. 6. 字符串内插