Assembly.GetType(“[. .]“,真的);抛出TypeLoadException
本文关键字:抛出 TypeLoadException 真的 GetType Assembly | 更新日期: 2023-09-27 18:08:33
我的代码:
//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[] { });
}
}
}
例外:类型为"System"的异常。在mscorlib.dll中发生typeloadeexception,但未在用户代码中处理
附加信息:Nie można załadować typu 'Engine.ModCrew。Mod' z zestawu '游戏,版本=0.0.0.0,文化=中性,PublicKeyToken=null'.
通过反射获取方法时应该始终使用BindingFlags
。
用MethodInfo.Invoke
调用实例需要实例作为第一个参数MethodInfo.Invoke(MyInstance,...)
基于注释的更改:
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
,以避免使用反射