.net6.0 新知识学习
C# 8语法:
?. 又称为空值传播运算符,用于在访问对象的属性或方法时,避免因为对象为null而导致的异常,它的作用是在访问属性或方法时先判断对象是否为null,如果不是null则返回属性或方法的值,如果是null则返回null。
例如,假设有一个Person对象,其中包含一个Name属性,如果我们想获取Name属性的值,则可以使用如下语句:
string name = person?.Name;如果person为null,那么name变量的值将为null。
?? 称为null合并运算符,用于在一个表达式为null时返回一个默认值。例如:
int num = x ?? 0;如果x为null,则num将为0,否则num将为x的值。
! 符号:在C# 8.0及更高版本中,!用于非空断言操作符。当你确信一个变量不会是null时,可以使用!来告诉编译器这个变量不是null。例如,var name = user!.Name;表示你确信user变量不是null,因此可以直接访问其Name`属性。如果变量实际上是null,这将导致运行时错误1。
string? nullableString = null; // 可空引用类型 int length5 = nullableString!.Length; // 使用非空断言运算符告诉编译器不进行 null 检查,结果:会报空异常 int length4 = nullableString?.Length?? 0; // 使用 空值传播运算符 和 null 合并运算符处理可能的 null 引用赋值 结果正常 int length3 = nullableString.Length; // 结果:会报空异常
//2、创建泛型主机 IHost host = hostBuilder.Build(); //3、获取IHostApplicationLifetime IHostApplicationLifetime lifetime = null; //3.1 应用程序启动后回调 结果:不会调用 lifetime?.ApplicationStarted.Register(OnStarted); //3.2 应用程序正在停止时回调 结果:不会调用 lifetime?.ApplicationStopping.Register(OnStopping); //3.3 应用程序已经停止时回调 结果:不会调用 lifetime?.ApplicationStopped.Register(OnStoped);
C# 构造函数链接、优先执行:的链接方法
Program.
using System;
namespace ConstructorChaining
{
class Circle
{
public Circle(int radius)
{
Console.WriteLine("Circle, r={0} is created", radius);
}
public Circle() : this(1)
{
}
}
class Program
{
static void Main(string[] args)
{
new Circle(5);
new Circle();
}
}
}
Student stu=new()
子类构造函数调用父类的构造函数使用: : Base(“111”)
同类函数调用类中的构造函数使用: : this(“111”)
监听器( 用途:统计执行过程的时间)
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 200000000; i++)
{
ShowInt(iValue);
}
watch.Stop();
commonSecond = watch.ElapsedMilliseconds;
C# 访问修饰符
| 类 | 当前程序集 | 派生类 | 当前程序集中的派生类 | 整个程序 | |
|---|---|---|---|---|---|
public |
+ | + | + | + | + |
protected |
+ | o | + | + | o |
internal |
+ | + | o | o | o |
private |
+ | o | o | o | o |
protected internal |
+ | + | + | + | o |
private protected |
+ | o | o | + | o |
新语法: Tool tool=new();
结构不能被继承,内部不能创建抽象方法;只可继承其他接口,不可继承其他类、抽象类、其他结构
指定泛型参数 必须派生于基类 SeniorAnimal
class MyList<T> where T : SeniorAnimal
{
...代码省略部分
}
拓展方法用法:
1、namespace 需要同一个命名控件(因为有个this的特性)
2、需要静态类+静态方法
3、可以定义多个类的拓展方法
using ClassLibrary1;
namespace ClassLibrary1
{
public static class PublicExtend
{
public static string GetClassName1(this ClsMain2 clsMain)
{
string str = clsMain.GetType() + " -- 拓展方法2";
Console.WriteLine(str);
return str;
}
}
}
特性的获取:类ClsMain被标记 [AttrTest] ,可以拿取到声明特性的各种信息 详细教程: https://blog.csdn.net/weixin_46785144/article/details/120630803
Type type = typeof(ClsMain);
if (type.IsDefined(typeof(AttrTestAttribute), true))
{
//此处获取的单个特性,可以使用GetCustomAttribute获取多个特性,即AttrTestAttribute的特性数组
AttrTestAttribute attrTestAttribute = (AttrTestAttribute)type.GetCustomAttribute(typeof(AttrTestAttribute), true); // 会实例化特性
Console.WriteLine(attrTestAttribute.Desc);
}
静态变量可以动态的设置

浙公网安备 33010602011771号