I need to call the different classes based on the requirement. For that, I have used Activator.CreateInstance() to achieve my goal. But, I can successfully access the specific class without passing the argument. But, while pass the argument I'm facing the problem. Here, I have posted my sample code.
class Program
{
private static readonly object[] activationAttributes;
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
ObjectHandle obj = Activator.CreateInstance("JsonGenerator", "JsonGenerator.MyClass2", true, System.Reflection.BindingFlags.Default, null, new object[] { "TestValue" }, null, activationAttributes); // Not working
//ObjectHandle obj = Activator.CreateInstance("JsonGenerator", "JsonGenerator.MyClass2"); // This kind of call work.
ParentClass parent = (ParentClass)obj.Unwrap();
parent.PerformFunction();
}
}
public abstract class ParentClass
{
public abstract void PerformFunction();
}
class MyClass1 : ParentClass
{
public MyClass1(object[] args)
{
}
public override void PerformFunction()
{
Console.WriteLine("Override insidet the class1");
}
}
class MyClass2 : ParentClass
{
public MyClass2(object[] args)
{
}
public override void PerformFunction()
{
Console.WriteLine("Override insidet the class2");
}
}
The below error message thrown while run the program
Unhandled exception. System.MissingMethodException: Constructor on type 'JsonGenerator.MyClass2' not found.
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstanceInternal(String assemblyString, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
It would be much appreciated if anyone can help on this.
Thanks,
To pass the string as argument, fixed my issue. Infact, the CreateInstance unpacked the object and invoked the corresponding constructor.
And,
Thanks,