【问题标题】:Activator.CreateInstance throws an exceptionActivator.CreateInstance 抛出异常
【发布时间】:2013-09-04 23:06:08
【问题描述】:

我有这门课:

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

【问题讨论】:

    标签: c# reflection activator


    【解决方案1】:

    这可能是因为您需要类型的全名。

    试试:return (ILogicEventListener)Activator.CreateInstance(type.Assembly.Location, type.FullName);

    也可以查看这个帖子:The type initializer for 'MyClass' threw an exception

    【讨论】:

      【解决方案2】:

      您将type.Name 作为参数传递,但PlaceLogicEventListener 只有一个隐式无参数构造函数。

      试试:

      Type type = typeof (PlaceLogicEventListener);
      Activator.CreateInstance(type);
      

      【讨论】:

        【解决方案3】:

        您还传递了错误的程序集名称 - 它需要显示名称。所以:

                Type type = typeof(PlaceLogicEventListener);
                var foo = (ILogicEventListener)Activator.CreateInstance(type.Assembly.FullName, type.FullName).Unwrap();
        

        应该这样做并解开从 CreateInstance 传回的 ObjectHandle。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-05-24
          • 2011-05-30
          • 1970-01-01
          • 2011-02-25
          • 2012-01-24
          相关资源
          最近更新 更多