首页 文章

C#/ Unity - 反射 - 对象与目标类型不匹配

提问于
浏览
2

我正在尝试使用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");
    }
}

这产生的输出是:

Type: GoldFate

MethodInfo: Void ResolveGoldFate()

TargetException: Object does not match target type. System.Reflection.MonoMethod.Invoke(System.Object obj,BindingFlags invokeAttr,System.Reflection.Binder binder,System.Object [] parameters,System.Globalization.CultureInfo culture)(at / Users / builduser / buildslave / mono-runtime -and-classlibs / build / mcs / class / corlib / System.Reflection / MonoMethod.cs:236)System.Reflection.MethodBase.Invoke(System.Object obj,System.Object [] parameters)(at / 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)

我显然没有看到调试消息

提前致谢

2 回答

  • 4

    以上解决方案,精简:

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

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

  • 2

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

相关问题