Activator.CreateInstance - How to create instances of classes that have parameterized constructors

后端 未结 5 1754
野性不改
野性不改 2020-12-24 12:21

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.

I use Acti

5条回答
  •  猫巷女王i
    2020-12-24 12:37

    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)

    Part of the code looks a little like this

    // If we have a ctor that requires parameters then pass null values
    if (requiresParameters)
    {
        List parameters = new List();
        ParameterInfo[] pInfos = constructorInfos[0].GetParameters();
    
        foreach (ParameterInfo pi in pInfos)
        {
            parameters.Add(createType(pi.ParameterType));
        }
    
        return constructorInfos[0].Invoke(parameters.ToArray());
    }
    
        

    提交回复
    热议问题