[ACCEPTED]-Activator.CreateInstance - How to create instances of classes that have parameterized constructors-.net-3.5
There is an overload that accepts arguments 2 as a params object[]
:
object obj = Activator.CreateInstance(typeof(StringBuilder), "abc");
Would this do? Alternative, you can 1 use reflection to find the correct constructor:
Type[] argTypes = new Type[] {typeof(string)};
object[] argValues = new object[] {"abc"};
ConstructorInfo ctor = typeof(StringBuilder).GetConstructor(argTypes);
object obj = ctor.Invoke(argValues);
I eventually ended up doing something like 7 this - some of the commentors hinted towards 6 this solution anyway.
I basically iterated 5 through all available constructors and chose 4 the simplest. I then created null data 3 to pass into the ctor (for what Im using 2 it for this approach is fine)
Part of the 1 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());
}
I'm using this method to get around an issue I ran into, and 1 it seems to be working exactly as I hoped. :)
object instance = Activator.CreateInstance(
typeof(OpCode),
BindingFlags.NonPublic | BindingFlags.Instance,
default(Binder),
new object[] { stringname, pop, push, operand, type, size, s1, s2, ctrl, endsjmpblk, stack },
default(CultureInfo));
Activator.CreateInstance also has a whole 8 bunch of overloads, one you might want to 7 check out is ( Type type, params object[] args 6 ). Simply supply the required constructor 5 arguments to the second parameter of this 4 call.
Make sure you handle exceptions here 3 though, as it's easy to pass incorrect parameters 2 in or for something to change in the type's 1 constructors later on that breaks it..
As an alternative to Activator.CreateInstance, FastObjectFactory 9 in the linked url preforms better than Activator 8 (as of .NET 4.0 and significantly better 7 than .NET 3.5. No tests/stats done with 6 .NET 4.5). See StackOverflow post for stats, info 5 and code. Note that some modifications may 4 need to be done based upon the number of 3 ctor params. The code provided only allows 2 1 ctor param but can be modified to have 1 more than 1. See comments in code.
How to pass ctor args in Activator.CreateInstance or use IL?
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.