使用反射的对象与单元中的目标类型不匹配

Object Does Not Match Target Type in Unit using Reflection

我正在尝试使用反射(对我来说是第一次,我已经查看了许多其他针对此错误的答案,但没有找到适合我的答案)

这里是调用方法

void OnMouseDown(){
    string CardName = "GoldFate";

    Type classType = Type.GetType(CardName);
    Debug.Log ("Type: " + classType);

    MethodInfo theMethod = classType.GetMethod("Resolve"+CardName);
    Debug.Log ("MethodInfo: " + theMethod);

    theMethod.Invoke(this, null);
}

这是目标:

public class GoldFate {
    public void ResolveGoldFate(){
        Debug.Log ("We got to Gold Fate");
    }
}

这生成的输出是:

类型:GoldFate

MethodInfo: 无效 ResolveGoldFate()

TargetException:对象与目标类型不匹配。 System.Reflection.MonoMethod.Invoke(System.Object obj,BindingFlags invokeAttr,System.Reflection.Binder 活页夹,System.Object[] 参数,System.Globalization.CultureInfo 文化)(在 /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:236) System.Reflection.MethodBase.Invoke(System.Object 对象,System.Object[] 参数)(位于 /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MethodBase.cs:115) FateCardManager.OnMouseDown () (位于 Assets/Scripts/Card Manipulation/FateCards/FateCardManager.cs:53) UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32, Int32)

我显然没有得到调试消息

提前致谢

我认为您的问题出在这一行:theMethod.Invoke(this, null);。这里的 this 需要是 GoldFate class 的实例。一旦您确定了这一点,我认为您将能够成功调用该方法。

以上解决方案,精简:

var myClass =   new MyClass();

var method =    myClass.GetType().GetMethod( "MyMethod" );
if ( method != null )
    method.Invoke( myClass, null );

感谢您的回答,我才能够在我的代码中使用它! <3