【问题标题】:Assembly.GetType("[...]", true); throws TypeLoadExceptionAssembly.GetType("[...]", true);抛出 TypeLoadException
【发布时间】:2016-09-24 15:16:50
【问题描述】:

我的代码:

//App, Core.cs
using System;
using System.IO;
using System.Reflection;

namespace Game
{
    public static void Main(string[] args)
    {
        Assembly a = Assembly.LoadFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mods\\ExampleMod.dll"));
        var x1 = a.GetType("PTF_Mod.Mod_Main");
        var x2 = x1.GetMethod("OnStart");
        var x3 = x2.Invoke(null, new object[] { });

        while(true);
    }
}


//App, ModCrew.cs
using System;
using System.Reflection;

namespace Engine
{
    public static class ModCrew
    {
        public class Mod
        {
            public void ItWorks()
            {
                Console.WriteLine("It works!");
            }
        }
    }
}

//DLL, Mod_Main.cs
using System;
using System.Reflection;

namespace PTF_Mod
{
    public static class Mod_Main
    {
        public static void OnStart()
        {
            var exe = Assembly.GetCallingAssembly();
            Console.WriteLine(exe.Location); //Location is valid
            var x = exe.GetType("Engine.ModCrew.Mod", true); //But here I get exception
            var y = Activator.CreateInstance(x);

            x.GetMethod("ItWorks", BindingFlags.Instance).Invoke(null, object[] { });
        }
    }
}

例外: mscorlib.dll 中出现“System.TypeLoadException”类型的异常,但未在用户代码中处理

附加信息:Nie można załadować typu 'Engine.ModCrew.Mod' z zestawu 'Game, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'。

【问题讨论】:

  • "Engine.ModCrew+Mod"
  • 然后 TypeLoadException on "var x3 = x2.Invoke(null, new object[] { });"在 Core.cs 中
  • "在 mscorlib.dll 中发生了 'System.TypeLoadException' 类型的异常,但未在用户代码中处理"
  • 哦,等一下,测试你的答案后,我忘记编译dll了
  • @TheChilliPL OnStart 不接受任何参数,改为使用x2.Invoke(null, null);

标签: c#


【解决方案1】:

在通过反射获取方法时,您应该始终使用BindingFlags

使用MethodInfo.Invoke调用实例需要实例作为第一个参数MethodInfo.Invoke(MyInstance,...)

基于 cmets 的变化:

public static void Main(string[] args)
{
    Assembly a = Assembly.LoadFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mods\\ExampleMod.dll"));
    var x1 = a.GetType("PTF_Mod.Mod_Main");
    var x2 = x1.GetMethod("OnStart", BindingFlags.Static | BindingFlags.Public);
    var x3 = x2.Invoke(null, null);

    while(true);
}

Mod_Main:

public static void OnStart()
{
    var exe = Assembly.GetCallingAssembly();
    Console.WriteLine(exe.Location); //Location is valid
    var x = exe.GetType("Engine.ModCrew+Mod", true); //But here I get exception
    var y = Activator.CreateInstance(x);

    x.GetMethod("ItWorks", BindingFlags.Instance | BindingFlags.Public).Invoke(y, null);
}

此外,考虑是否需要反射,它会使程序过于复杂。如果有必要,您应该查看Dynamic 以避免使用反射调用方法的许多麻烦

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多