“Object does not match target type” when calling methods using string in C#

巧了我就是萌 提交于 2019-12-29 08:47:06

问题


I'm trying to call a method using a string, but there a problem:

void make_moviment(string mov,Vector3 new_mov){
    GameObject past_panel = GameObject.Find(actual_level.ToString());
    Type t = Type.GetType(past_panel.GetComponents<MonoBehaviour>()[0].GetType ().Name);
    MethodInfo method = t.GetMethod("get_answer");
    method.Invoke(t,new object[] { mov }));   <--- PROBLEM HERE
}

There's always this error "Object does not match target type" related with the last line. Do you have any recommendations?


回答1:


method.Invoke(t,new object[] { mov }));

Is the same as calling

t.WhateverTheMethodIs(mov);

But t is the Type, not the object of that type. You need to pass in the object to call the method on there instead. (Or null if the method is static).



来源:https://stackoverflow.com/questions/41970341/object-does-not-match-target-type-when-calling-methods-using-string-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!