首页 > 解决方案 > C#可以为空吗类型在 MakeByRefType 之后保留有关内部类型的信息?

问题描述

我正在尝试使用反射创建具有私有(或更确切地说是内部)构造函数的对象实例:

internal static T CreateInstance<T>(Type[] types, params object[] args)
{
    var ctor = typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);
    if (ctor != null) 
        return (T) ctor.Invoke(args);
    throw new InvalidOperationException("No constructor available with specified argument types to reflect.");

此代码适用于大多数情况,但对于以下构造函数(来自 VulkanCore 库)失败:

internal SurfaceKhr(Instance parent, ref AllocationCallbacks? allocator, long handle)

如果您列出构造函数的 ParameterInfo 对象,这代表它自己:

parent, VulkanCore.Instance, allocator, System.Nullable`1[VulkanCore.AllocationCallbacks]&, handle, System.Int64

但是,如果您检查:new []{typeof(Instance), typeof(Nullable<AllocationCallbacks>).MakeByRefType(), typeof(Int64)}for的类型信息types,它会产生:Instance, Nullable`1&, Int64。检查等效类型时,这是相同的输出:typeof(AllocationCallbacks?).MakeByRefType().

有没有办法在ref AllocationCallbacks?通过 查找构造函数时保留内部类以供使用typeof(T).GetConstructor(...)

标签: c#reflectionconstructorpass-by-referencesystem.reflection

解决方案


推荐阅读