![](/img/trans.png)
[英]Activator.CreateInstance throws MissingMethodException in 1 solution but not another
[英]Activator.CreateInstance throws 'System.MissingMethodException' when using CoreCLR
我正在嘗試在CoreCLR應用程序中創建一個類的實例,但是當我調用Activator.CreateInstance時,我得到了System.MissingMethodException,說它在嘗試創建的類上找不到構造函數。 該類確實具有構造函數。 我究竟做錯了什么?
該項目僅針對dnxcore50。
這是代碼:
using System;
namespace MyNamespace
{
public class Program
{
public void Main(string[] args)
{
Activator.CreateInstance(typeof (MyClass), true);
}
}
public class MyClass
{
public MyClass() { }
}
}
這是一個例外:
System.MissingMethodException was unhandled by user code
HResult=-2146233069
Message=Constructor on type 'MyNamespace.MyClass' not found.
Source=mscorlib
StackTrace:
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
at MyNamespace.Program.Main(String[] args) in C:\projects\coreclrplayground\InvokeMember\src\InvokeMember\Program.cs:line 9
InnerException:
在CoreCLR上, Activator
沒有接受布爾值的重載,該參數指示是否可以使用非公共構造函數來實例化類型。
您的代碼段正確構建是因為編譯器選擇了CreateInstance(Type type, params object[] args)
重載,該重載將布爾值視為構造函數參數:由於構造函數是無參數的,因此會引發異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.