2015-10-07 39 views
1

我想將一些參數傳遞給在通用Windows App中使用反射調用的函數。下面是我嘗試的代碼,我收到一個異常「參數計數不匹配」。請指教我。在反射中傳遞參數Windows存儲應用程序

public class myClass 
{ 
    public async void btn_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) 
    { 
     Type type = Type.GetType("moto_Windows.Actions.NextViewAction");     
     object[] mParam = new object[] { 5, 10 }; 
     var nva = Activator.CreateInstance(type); 
     await (dynamic)type.GetTypeInfo().GetDeclaredMethod("NextView").Invoke(nva, mParam); 
    } 
} 

我試圖調用看起來像下面

namespace moto_Windows.Actions 
{ 
    public class NextViewAction 
    { 
    public NextViewAction(object [] obj) 
    { 
     //Constructor   
    } 
    public async void NextView() 
    { 
     //Method to be invoked. 
    } 
} 
} 
+1

你的構造函數有需要的參數,而你沒有傳遞它們。然後對於該方法,當方法沒有時傳遞參數。 – WiredPrairie

回答

0

最後我解決了這個在字典中傳遞值通過構造器的類,我的代碼是

Type type = Type.GetType("moto.Actions." + ctrl.Action.name); 
ctrl = (Carrot_Control)btn.DataContext; 
Dictionary<string, object> _dict = new Dictionary<string, object>(); 
dict.Add("a", 5); 
_dict.Add("b", 10); 
var t = Activator.CreateInstance(type, _dict); 
await (dynamic)type.GetTypeInfo().GetDeclaredMethod("NextView").Invoke(t, null); 

和我試圖調用的課程

namespace moto_Windows.Actions 
{ 
public class NextViewAction 
{ 
public NextViewAction(Dictionary<string,object> _dict) 
{ 
    //Constructor   
    string a = _dict[a]; 
    string b = _dict[b]; 
} 
public async void NextView() 
{ 
    //Method to be invoked. 
} 
} 
} 

如果有人有更好的答案,請發佈。

相關問題