佛缘一生 发表于 2023-7-26 15:40:52

C# ?的7种用法

1. 可空类型修饰符?

int i? num=null;//表示可空的整型
DateTime time? dateTime=null; //表示可空的时间2.三元(运算符)表达式?:

x?y:z //表示如果表达式x为true,则返回y,如果x为false,则返回z,是省略if{}else{}的简单形式。3.NULL检查运算符?.

int? first = customers?.Orders.Count();(1)?[ ]

int? first = customers?.Orders.Count();(2)?[]?

public static Delegate? Combine(params Delegate?[]? delegates)
{
    if (delegates == null || delegates.Length == 0)
      return null;

    Delegate? d = delegates;
    for (int i = 1; i < delegates.Length; i++)
      d = Combine(d, delegates);

    return d;
}
//params Delegate?[] delegates -它是可为空的数组 Delegate

//params Delegate?[]? delegates -整个数组可以为空4.空合并运算符??

(1)??

//用于定义引用类型和可空类型的默认值。如果此运算符的左操作数不为Null,则此操作符将返回左操作数,否则返回右操作数。

var c = a??b //当a不为null时返回a,为null时返回b(2)null 合并赋值运算符??=

仅当左操作数计算为 null 时,才能使用运算符 ??= 将其右操作数的值分配给左操作数。
List<int> numbers = null;
int? i = null;

numbers ??= new List<int>();
numbers.Add(i ??= 17);
numbers.Add(i ??= 20);

Console.WriteLine(string.Join(" ", numbers));// output: 17 17
Console.WriteLine(i);// output: 17
来源:https://www.cnblogs.com/MasonZhao/archive/2023/07/26/17582743.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: C# ?的7种用法