gpt4 book ai didi

c# - 使用反射在内部类中实例化带参数的构造函数

转载 作者:IT王子 更新时间:2023-10-29 03:49:48 27 4
gpt4 key购买 nike

我有一些类似的东西:

object[] parameter = new object[1];
parameter[0] = x;
object instantiatedType =
Activator.CreateInstance(typeToInstantiate, parameter);

internal class xxx : ICompare<Type>
{
private object[] x;

# region Constructors

internal xxx(object[] x)
{
this.x = x;
}

internal xxx()
{
}

...
}

然后我得到:

抛出异常:System.MissingMethodException:找不到类型为“xxxx.xxx”的构造函数..

有什么想法吗?

最佳答案

问题是 Activator.CreateInstance(Type, object[])不考虑非公共(public)构造函数。

Exceptions

MissingMethodException: No matching public constructor was found.

这很容易通过将构造函数更改为public可见性来显示;然后代码可以正常工作。

这是一种解决方法(已测试):

 BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
CultureInfo culture = null; // use InvariantCulture or other if you prefer
object instantiatedType =
Activator.CreateInstance(typeToInstantiate, flags, null, parameter, culture);

如果您只需要无参数构造函数,这也可以:

//using the overload: public static object CreateInstance(Type type, bool nonPublic)
object instantiatedType = Activator.CreateInstance(typeToInstantiate, true)

关于c# - 使用反射在内部类中实例化带参数的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4077253/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com