获取类型默认构造函数的最有效方法 [英] Most efficient way to get default constructor of a Type

查看:36
本文介绍了获取类型默认构造函数的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取 System.Type 的默认构造函数(即没有参数的实例构造函数)的最有效方法是什么?

What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type?

我正在考虑下面的代码行,但似乎应该有一种更简单更有效的方法来做到这一点.

I was thinking something along the lines of the code below but it seems like there should be a simplier more efficient way to do it.

Type type = typeof(FooBar)
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
type.GetConstructors(flags)
    .Where(constructor => constructor.GetParameters().Length == 0)
    .First();

推荐答案

type.GetConstructor(Type.EmptyTypes)

这篇关于获取类型默认构造函数的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆