Skip to content
标签
欢迎扫码关注公众号

C# Activator.CreateInstance vs default

1. Activator.CreateInstance(Type)

Creates an instance of the specified type using that type's default constructor.

另外该方法还有几个重载 CreateInstance(Type, Object[]) 也是调用匹配的构造函数创建实例。

Creates an instance of the specified type using the constructor that best matches the specified parameters.

如果类型没有对应的构造函数则会报错,比如 String 就没有无参的构造函数。下面的代码如果传入 String 型就会报错。

csharp
(T)Activator.CreateInstance(typeof(T))

2. default(T)

默认值表达式 default(T) 生成 T 类型的默认值。下表显示为各种类型生成的值:

类型默认值
任何引用类型null
数值类型
boolfalse
char'\0'
enum表达式 (E)0 生成的值,其中 E 是枚举标识符。
struct通过如下设置生成的值:将所有值类型的字段设置为其默认值,将所有引用类型的字段设置为 null。
可以为 null 的类型HasValue 属性为 falseValue 属性未定义的实例。

从 C# 7.1 开始,当编译器可以推断表达式的类型时,文本 default 可用于默认值表达式。文本 default 生成与等效项 default(T)(其中,T 是推断的类型)相同的值。这可减少多次声明类型的冗余,从而使代码更加简洁。文本 default 可用于以下任一位置:

  • 变量初始值设定项
  • 变量赋值
  • 声明可选参数的默认值
  • 为方法调用参数提供值
  • 返回语句(或 expression bodied 成员中的表达式)

参考

  1. 【C#】Activator.CreateInstance 用法
  2. C# 7.1 中 default 关键字的新用法
  3. 默认值表达式(C# 编程指南)
  4. CreateInstance(Type)

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.