[英]Calling a method dynamically with the right arguments
首先,答案不是
.Invoke("name", new object[] { });
:)話雖如此,我有一些舊的通用代碼,這些代碼使用配置文件中的定義創建上下文菜單和熱鍵處理程序,並使用.Invoke()執行實際方法,其中方法簽名是預定義的,否則方法不是被執行
例如,方法簽名與這些參數都相同
change_back_color( mycontext ctx, object sender, controlItemClickEventArgs e)
{
//...
}
我必須重新編寫代碼以包括一些其他功能,並希望擁有類似Unity / MEF的功能,其中簽名只能包含所需的參數,並且參數的順序可以更改
例如,代碼可以更改為
[FunctionKey("myKey1")]
change_back_color( object sender, mycontext ctx )
{
//...
}
要么
[FunctionKey("myKey1")]
change_back_color( mycontext ctx)
{
//...
}
尋找有關如何/在哪里尋找的指導
更新-定義在db中,可以像這樣檢索
var commands = dbContext.GetCommands("current_view_name") ; // return method key, user roles etc.
// and i can use the following to match to "current_view_name"
[ImportMany(RequiredCreationPolicy=CreationPolicy.NonShared)]
public IEnumerable<Lazy<MenuItem,IDictionary<string,object>> MenuItems
{
set
{
var fooMenuItems = value
.Where(x => x.Metadata["ContextTarget"] == "current_view_name")
.Select(x => x.Value);
// attach fooMenuItems to some context menu...
}
}
但是這些方法也需要一些自定義參數! 有任何想法嗎 ?
如果您想通過MEF將上下文菜單動態添加到您的應用程序中,我將執行以下操作:
[Export(typeof(MenuItem)]
[ExportMetadata("ContextTarget", "foo")]
public FooMenuItemForBarAction
{
get
{
var menuItem = new MenuItem("BarAction");
menuItem.Click += delegate
{
// code to handle click here
}
return menuItem;
}
}
然后可以在其他位置導入“ foo”的所有上下文菜單項,如下所示:
[ImportMany(RequiredCreationPolicy=CreationPolicy.NonShared)]
public IEnumerable<Lazy<MenuItem,IDictionary<string,object>> MenuItems
{
set
{
var fooMenuItems = value
.Where(x => x.Metadata["ContextTarget"] == "foo")
.Select(x => x.Value);
// attach fooMenuItems to some context menu...
}
}
對於熱鍵處理程序,您可以執行類似的操作:將導出/導入的類型更改為Action
然后用鍵組合替換元數據。 然后,當用戶按下組合鍵時,您可以使用正確的元數據掃描所有導入,並執行該操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.