[英]Activator.CreateInstance throws 'System.MissingMethodException' when using CoreCLR
[英]Activator.CreateInstance() throw System.MissingMethodException while create the instance C#
我需要根據要求調用不同的類。 為此,我使用了 Activator.CreateInstance() 來實現我的目標。 但是,我可以在不傳遞參數的情況下成功訪問特定的 class 。 但是,在通過論點時,我面臨着問題。 在這里,我發布了我的示例代碼。
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");
}
}
運行程序時拋出以下錯誤消息
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)
如果有人可以提供幫助,將不勝感激。
謝謝,
要將字符串作為參數傳遞,解決了我的問題。 實際上,CreateInstance 解壓了 object 並調用了相應的構造函數。
public MyClass1(string args)
{
}
和,
public MyClass2(string args)
{
}
謝謝,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.