Activator.CreateInstance - 如何创建具有参数的构造函数的类的实例

Activator.CreateInstance  - 如何创建具有参数的构造函数的类的实例

问题描述:

我已经阅读了几个位和鲍勃网上关于这个话题,但发现没有一个为我工作。 我所要做的是创建一个类的运行时类型。

I have read a few bits and bobs online about this topic but found none that work for me. What I am trying to do is create a class of a runtime Type.

我用 Activator.CreateInstance 它的类的包含无参数的构造函数工作正常。对于那些参数,它抛出一个异常,有没有解决的办法?

I use Activator.CreateInstance which works fine for classes with constructors that contain no arguments. For those with arguments it throws an exception, is there a way around this?

我很乐意,只要我可以创建类本身为空值或空值传递给构造函数。

I am more than happy to pass null values or empty values to the ctor so long as I can create the class itself.

我终于结束了做这样的事情 - 一些评论者的暗示对这一解决方案,反正

I eventually ended up doing something like this - some of the commentors hinted towards this solution anyway.

我所有可用的构造基本迭代,并选择最简单的。然后,我创建了空数据传递到构造函数(利用它的这种做法进出口什么是好的)

I basically iterated through all available constructors and chose the simplest. I then created null data to pass into the ctor (for what Im using it for this approach is fine)

的code部分看起来有点像这样

Part of the code looks a little like this

// If we have a ctor that requires parameters then pass null values
if (requiresParameters)
{
    List<object> parameters = new List<object>();
    ParameterInfo[] pInfos = constructorInfos[0].GetParameters();

    foreach (ParameterInfo pi in pInfos)
    {
        parameters.Add(createType(pi.ParameterType));
    }

    return constructorInfos[0].Invoke(parameters.ToArray());
}