Activator.CreateInstance引发异常
本文关键字:异常 CreateInstance Activator | 更新日期: 2023-09-27 18:29:46
我有这个类:
public class PlaceLogicEventListener : ILogicEventListener
{
}
我有这样的代码试图通过反射创建一个实例:
public ILogicEventListener GetOne(){
Type type = typeof (PlaceLogicEventListener);
return (ILogicEventListener)Activator.CreateInstance(type.Assembly.Location, type.Name);
}
我得到以下异常:
System.TypeInitializationException : The type initializer for 'CrudApp.Tests.Database.DatabaseTestHelper' threw an exception.
----> System.IO.FileLoadException : Could not load file or assembly 'C:''Users''xxx''AppData''Local''Temp''vd2nxkle.z0h''CrudApp.Tests''assembly''dl3''5a08214b''fe3c0188_57a7ce01''CrudApp.BusinessLogic.dll' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
我正在从测试dll调用GetOne()
。PlaceLogicEventListener
和方法GetOne()
的代码都在同一个组件CrudApp.BusinessLogic.dll
中
这可能是因为您需要类型的全名。
尝试:return (ILogicEventListener)Activator.CreateInstance(type.Assembly.Location, type.FullName);
还要检查这个线程:';MyClass';引发异常
您将type.Name
作为参数传递,但PlaceLogicEventListener
只有一个隐式无参数构造函数。
尝试:
Type type = typeof (PlaceLogicEventListener);
Activator.CreateInstance(type);
您还传入了错误的assembyly名称-它需要显示名称。因此:
Type type = typeof(PlaceLogicEventListener);
var foo = (ILogicEventListener)Activator.CreateInstance(type.Assembly.FullName, type.FullName).Unwrap();
应该执行此操作,并且还应该取消对从CreateInstance传递回来的ObjectHandle的拖动。