C#的"?"修饰符和"??"运算符

一.  ?  可空类型修饰符

“?”用来修饰为空的值类型,在加上“?”修饰符后,值类型也可以为空了,如:

public int? CommandTimeout { get; };
var prop = new PropertyInfo();

prop?.CanWrite == true;
public CommandDefinition(string commandText, object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null,CommandType? commandType = null)

还有一点需要知道,编译的时候,加上“?”修饰符的值类型会被转换为:

// 支持的值类型,可以分配 null。 此类不能被继承。
[ComVisible(true)]
public static class Nullable

二.  ??  空合并运算符

 “??”用于运算可为空类型和引用类型的最终值,如:

templates = templates ?? new List<object>();

代码中,如果templates不为空,则返回自身,如果templates为空,则重新实例化。

原文地址:https://www.cnblogs.com/vurtne/p/7611964.html