三元运算符 ?:
使用前
cs
int value = -2;
if (value < 0)
{
value = 0;
}
else
{
value = 1;
}
使用后
cs
int value = -2;
value = value < 0 ? 0 : 1;
Null 合并操作符 ??
使用前
cs
string value = GetString();
if (value == null)
{
value = "Empty";
}
使用后
如果左操作数的值不为null,则 null 合并运算符 ?? 返回该值;否则,它会计算右操作数并返回其结果。 如果左操作数的计算结果为非 null,则?? 运算符不会计算其右操作数。
cs
string value = GetString() ?? "Empty";
内插字符串 $
字符串内插为格式化字符串提供了一种可读性和便捷性更高的方式。 它比字符串复合格式设置更容易阅读。
使用前
cs
string name = "小明";
int age = 18;
string.Format("大家好,我叫{0},今年{1}岁。", name, age);
使用后
cs
string name = "小明";
int age = 18;
var format = $"大家好,我叫{name},今年{age}岁。";
Null 条件运算符 ?.
如果对象为NULL,则不执行?.后面的逻辑
使用前
cs
Action action;
if (action != null)
{
action.Invoke();
}
使用后
cs
Action action;
action?.Invoke();
可空类型修饰符 ?
引用类型可以使用空引用表示一个不存在的值,而值类型通常不能表示为空。
例如:string str=null; 是正确的,int i=null; 编译器就会报错。
使用可空类型修饰符?可以让值类型变量赋值null
cs
int? value = 0;
value = null;
using
当离开 using
语句块时,将释放获取的IDisposable实例。 using
语句可确保即使在 using
语句块内发生异常的情况下也会释放可释放实例。
使用前
cs
StreamReader reader = null;
try
{
reader = File.OpenText("numbers.txt");
}
finally
{
reader?.Dispose();
}
使用后
cs
using (StreamReader reader = File.OpenText("numbers.txt"))
{
}