首页 > 解决方案 > 我可以在 .NET Core 中获取私有构造函数吗?

问题描述

在 .NET Framework 中存在这样的方法:

public ConstructorInfo GetConstructor(
    BindingFlags bindingAttr,
    Binder binder,
    CallingConventions callConvention,
    Type[] types,
    ParameterModifier[] modifiers
)

但在 .NET Core (1.1) 中,我发现只有扩展,它没有给我私有构造函数:

public static ConstructorInfo GetConstructor(this Type type, Type[] types)

所以我想知道我是否可以在 .NET Core 中以某种方式访问​​和获取私有构造函数。

标签: c#reflection.net-core

解决方案


使用TypeInfo.DeclaredConstructors.

根据文档,它适用于 .NET Core 1.1(和其他)。

您应该使用GetTypeInfo().DeclaredConstructorsLINQ 过滤器来找到所需的构造函数。


推荐阅读