2017-07-21 78 views
1

我不斷收到錯誤:「類型」不包含定義「GetMethod」

CS1061: 'Type' does not contain a definition for 'GetMethod' and no extension method 'GetMethod' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?).

我試圖構建Windows應用商店的應用程序!

這裏是我的代碼:

MethodInfo theMethod = itween.GetType().GetMethod (animation.ToString(), new Type[] { 
     typeof(GameObject), 
     typeof(Hashtable) 
}); 
theMethod.Invoke(this, parameters); 

回答

2

要在Windows商店應用中使用反射,所屬類別類是用來代替類型類,這是經典的.NET應用程序中使用。

但是,它仍然有一些限制:

In a Windows 8.x Store app, access to some .NET Framework types and members is restricted. For example, you cannot call .NET Framework methods that are not included in .NET for Windows 8.x Store apps, by using a MethodInfo object.

參考:Reflection in the .NET Framework for Windows Store Apps

相當於你的代碼段是這樣的:

using System.Reflection; //this is required for the code to compile 

var methods = itween.GetType().GetTypeInfo().DeclaredMethods; 
foreach (MethodInfo mi in methods) 
{ 
    if (mi.Name == animation.ToString()) 
    { 
     var parameterInfos = mi.GetParameters(); 
     if (parameterInfos.Length == 2) 
     { 
      if (parameterInfos[0].ParameterType == typeof(GameObject) && 
       parameterInfos[1].ParameterType == typeof(Hashtable)) 
      { 
       mi.Invoke(this, parameters) 
      } 
     } 
    } 
} 

注意GetTypeInfo被定義爲擴展方法,因此編譯器需要using System.Reflection;才能識別此方法。