C# System.Reflection.TargetException:对象与目标类型不匹配
我在一个目录中有两个紧挨着的DLL。当我加载一个程序集时,将一个方法从DLL a调用到DLL B,然后将一个方法从DLL B调用回DLL a,但在最后一步失败并抛出以下错误C# System.Reflection.TargetException:对象与目标类型不匹配,c#,dll,reflection,C#,Dll,Reflection,我在一个目录中有两个紧挨着的DLL。当我加载一个程序集时,将一个方法从DLL a调用到DLL B,然后将一个方法从DLL B调用回DLL a,但在最后一步失败并抛出以下错误 System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetException: Object does not
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetException: Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at ServerSDK.BootStrapper.GetPlayerSteamID(UInt16 playerid)
这是代码
public void Init()
{
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string file = Path.Combine(assemblyFolder, "NetworkSystem.dll");
Assembly assembly = Assembly.LoadFile(file);
type = assembly.GetType("ScriptingAPI.ScriptEngine");
getSteamMethod = type.GetMethod("GetSteamID", new Type[] { typeof(ushort) });
Console.WriteLine("bootstrap module executed");
}
public static string GetPlayerSteamID(ushort playerid)
{
var steamid = getSteamMethod.Invoke((object)type, new object[1] { playerid });
return steamid.ToString();
}
这是我试图从DLL A调用的方法
public string GetSteamID(ushort playerID)
{
Console.WriteLine(playerID.GetType().Name);
return connectedPlayers[playerID].steamID;
}
另外,我觉得我需要像Activator.GetInstance这样的东西,而不是CreateInstance,因为DLL已经在运行,如果我使用CreateInstance,它会反过来抛出空引用异常。好的,所以在这种情况下,我的解决方案是将调用Init的对象作为参数传递给它。谢谢你的回复 你的问题不是很清楚。能否显示在DLL a中调用方法的代码、在DLL B中调用方法的代码以及在这两个DLL中调用的代码。另外,
CreateInstance()
创建类型的实例,而不是程序集,因此使用它是正确的。您当前正在尝试对该类型而不是该类型的实例调用方法。听起来您需要获取对ScriptEngine
的现有实例的引用,但如果不了解更多信息,我们就无法为您提供更多帮助。@DaisyShipton是的,没错,但我一点也不知道如何才能做到这一点。如果我将对象的引用作为Init的一个参数传递,那么在调用它之后,它会被保留吗?我不确定这里的“保留”是什么意思-但是你比我们有更多的上下文。如果您有一个对正确对象的引用,那么是的,您应该能够调用该对象上的方法。在这种情况下,您真的需要使用反射吗?(为了避免调用obj.GetType()
而不是加载程序集等)@DaisyShipton我确实认为我需要使用反射,原因是我试图允许最终用户通过“脚本”自定义他们的应用程序,这似乎比嵌入pawn或python之类的东西容易得多。我所说的保留是指,如果一个程序集对一个对象的引用实际上是通过invoke发送的,而不是它的副本等。但事实证明,我所建议的是可行的。我很感激你抽出一天的时间来帮助我。