【问题标题】:"Object does not match target type" when calling methods using string in C#在 C# 中使用字符串调用方法时出现“对象与目标类型不匹配”
【发布时间】:2017-06-17 15:25:47
【问题描述】:

我正在尝试使用字符串调用方法,但是出现了问题:

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
}

总是有这个错误“对象与目标类型不匹配”与最后一行有关。你有什么建议?

【问题讨论】:

  • 请出示get_answer的签名。
  • 您正试图在 Type 类型的对象(即变量 t)上调用 get_answer 方法。很难说出你想要做什么,但看起来你想对 past_panel.GetComponents&lt;MonoBehaviour&gt;()[0] 执行它。
  • 感谢@DavidG 成功了!

标签: c# string methods reflection invoke


【解决方案1】:
method.Invoke(t,new object[] { mov }));

和调用一样

t.WhateverTheMethodIs(mov);

但是tType,而不是那种类型的对象。您需要传入对象以调用那里的方法。 (如果方法是静态的,则为 null)。

【讨论】:

  • 谢谢你!刚刚从 "t" 更改为 "past_panel.GetComponents()[0]" 并且成功了!
  • 酷。如果此答案解决了您的问题,您可以单击左上角的勾号将其标记为已解决。
猜你喜欢
  • 2019-02-25
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-06
  • 1970-01-01
相关资源
最近更新 更多