2013-10-17 34 views
1

我正在開發一個Windows Phone應用程序,並將其定位到7.1,因此它可以在wp7和wp8設備上運行。 如果應用一個WP8設備上運行時,我想運行此代碼:GetFileAsync然後通過反射調用Windows.System.Launcher.LaunchFileAsync

public async void DefaultLaunch2a() 
{ 
    // Path to the file in the app package to launch 
    var file1 = await ApplicationData 
     .Current 
     .LocalFolder 
     .GetFileAsync("webcam-file.jpg"); 

    if (file1 != null) 
    { 
     // Launch the retrieved file 
     var success = await Windows.System.Launcher.LaunchFileAsync(file1); 

     if (success) 
     { 
      // File launched/y 
     } 
     else 
     { 
      // File launched/n 
     } 
    } 
    else 
    { 
     // Could not find file 
    } 
} 

啓動器的文件類型(打開的圖像)。我正在嘗試通過反思來實現,但我遇到了一些問題。

String name = "file1.jpg"; 
Type taskDataType2 = Type.GetType("Windows.Storage.StorageFolder, Windows, " 
            + "Version=255.255.255.255, Culture=neutral, " 
            + "PublicKeyToken=null, " 
            + "ContentType=WindowsRuntime"); 

MethodInfo showmethod2 = taskDataType2.GetMethod("GetFileAsync", 
               new Type[] 
               { 
                typeof(System.String) 
               }); 
showmethod2.Invoke(taskDataType2, 
        new System.String[] { name }); 

此代碼拋出異常TargetException: Object does not match target type - 當調用該方法。

出了什麼問題?有沒有人試圖用反射來編寫上面的代碼? 目標是從設備商店中讀取圖像文件,然後啓動Windows.System.Launcher.LaunchFileAsync。 如果代碼在wp8設備上運行,我想要做一些類似mangopollo的操作。

回答

1

問題在於,您應該調用taskDataType2實例上的方法,而不是表示類型的對象。 taskDataType2不是Windows.Storage.StorageFolder的實例,它是Type類型的實例。試試這樣的:

Type taskDataType2 
    = Type.GetType("Windows.Storage.StorageFolder, Windows," 
        + " Version=255.255.255.255, Culture=neutral," 
        + " PublicKeyToken=null, ContentType=WindowsRuntime"); 

MethodInfo showmethod2 = taskDataType2 
    .GetMethod("GetFileAsync", new[] { typeof(string) }); 

object taskDataInstance = taskDataType2 
    .GetConstructor(Type.EmptyTypes) 
    .Invoke(null);  

String name = "file1.jpg"; 
showmethod2.Invoke(taskDataInstance, new[] { name }); 

這被簡化爲當該類型可以用無參數構造函數實例化的情況。否則,應使用適當的參數而不是Type.EmptyTypes調用GetConstructor

請注意,這不是檢索StorageFolder實例recommended方式:

通常情況下,您可以訪問StorageFolder對象爲異步方法和/或函數調用的結果。例如,靜態方法GetFolderFromPathAsync返回代表指定文件夾的StorageFolder