我的代码:
//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”类型的异常,但未在用户代码中处理
其他信息:Niemożnazaładowaćtyxu'Engine.ModCrew.Mod'zzestawu'Game,Version = 0.0.0.0,Culture = neutral,PublicKeyToken = null'。
答案 0 :(得分:1)
通过反射获取方法时,应始终使用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
以避免使用反射调用方法的许多麻烦