System.Reflection.TargetException:Object与目标类型不匹配

时间:2018-04-11 12:59:19

标签: 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 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,它将反过来抛出空引用异常。

1 个答案:

答案 0 :(得分:1)

好的,所以在这种情况下我的解决方案是将调用Init的对象作为参数传递给它。谢谢你的回复!