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

时间:2015-08-30 06:22:34

标签: c# reflection unity3d

我正在尝试使用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:Void ResolveGoldFate()

TargetException:对象与目标类型不匹配。 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-和-classlibs /建造/ MCS /类/ corlib /的System.Reflection / MonoMethod.cs:236) System.Reflection.MethodBase.Invoke(System.Object obj,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)

我显然没有看到调试消息

提前致谢

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

以上解决方案,精简:

var myClass =   new MyClass();

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

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