C#11--14新特性
1、定义属性使用field关键字
2、赋值时null判断简化
3、扩展属性、静态方法
4、多行字符串定义
5、Lock对象应用
6、集合简化初始化 [...]
using System.Runtime.Serialization;
using System.ComponentModel;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.CompilerServices;
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ABC
{
get;
set
{
//使用field,简化属性定义
field = value;
if (value == "hello")
Console.WriteLine("hello world");
}
}
private Lock _lock = new Lock();
private void button1_Click(object sender, EventArgs e)
{
Button button = null;
//支持赋值语句的空值判断 少些一行if代码
button?.Text = "hello";
ABC = "123";
ABC = "hello";
var list = new List<string>();
if (list.IsEmpty)
Console.WriteLine("this list is empty");
Console.WriteLine($"{list.GetCount()}");
var emptyList = List<int>.GetEmptyInstence();
Console.WriteLine($"{emptyList.IsEmpty}");
emptyList.Add(1);
Console.WriteLine($"{emptyList.IsEmpty}");
//简化using用法
using ADisposableObj obj = new ADisposableObj();
obj.SayHello();
//新的Lock对象
lock (_lock)
{
//todo
}
using (_lock.EnterScope())
{
//todo
}
//尝试获取锁
while (true)
{
var isOk = _lock.TryEnter();
if (!isOk)
{
Thread.Sleep(10);
continue;
}
try
{
//todo
}
finally
{
_lock.Exit();
}
break;
}
//集合表达式
List<int> aList = [1, 2, 3, 4];
Console.WriteLine(string.Join(",", aList));
//多行字符串定义 A\B\C前面的空格给去掉了,后面的换行符保留
var str = """
A
B
C
""";
MessageBox.Show(str);
}
}
public static class ListExtension
{
extension<T>(List<T> list)
{
/// <summary>
/// 扩展属性
/// </summary>
public bool IsEmpty => list.Count == 0;
/// <summary>
/// 扩展方法
/// </summary>
/// <returns></returns>
public int GetCount() => list.Count;
/// <summary>
/// 扩展静态函数
/// </summary>
/// <returns></returns>
public static List<T> GetEmptyInstence() => new List<T>();
}
}
public class ADisposableObj : IDisposable
{
private AutoResetEvent _resetEvent = new AutoResetEvent(false);
public void SayHello()
{
Console.WriteLine("Hello");
}
public void Dispose()
{
_resetEvent?.Dispose();
}
}
}