c# 常用操作符

目录

1、nameof

2、??

3、default 默认值

4、is

5、as



1、nameof

可输出方法、类、属性、变量的名称,

class Program
{
    static void Main(string[] args)
    {
        WriteLine(nameof(Student));
        WriteLine(nameof(Student.Roll));
        WriteLine(nameof(Student.Name));
        WriteLine(nameof(Student.Address));
    }
}

class Student
{
    public int Roll { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
}

输出==》

这样当我们写日志时就不需要向下面写法输出当前类名或方法

Log.Info("类名+方法名")

 

2、??

如果左操作数的值不为 null,则 null 合并运算符 ?? 返回该值;否则,它会计算右操作数并返回其结果。 如果左操作数的计算结果为非 null,则 ?? 运算符不会计算其右操作数

int? a = null;
int b = a ?? -10;
Console.WriteLine(b);  // output: -10

int c= a ?? 10;
Console.WriteLine(b);  // output: -10

 

3、default 默认值

default value 表达式生成类型的默认值

Console.WriteLine(default(int));  // output: 0
Console.WriteLine(default(object) is null);  // output: True

4、is

用于检查表达式的运行时类型是否与给定类型兼容

int i = 27;
Console.WriteLine(i is System.IFormattable);  // output: True

object iBoxed = i;
Console.WriteLine(iBoxed is int);  // output: True
Console.WriteLine(iBoxed is long);  // output: False

5、as

as 运算符将表达式结果显式转换为给定的引用或可以为 null 值的类型。 如果无法进行转换,则 as 运算符返回 null。 与强制转换表达式 不同,as 运算符永远不会引发异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值