[英]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.