简体   繁体   English

在运行时动态创建后备委托

[英]Dynamically create fallback delegate at runtime

I'm trying to setup C# code to automatically create dummy or fallback delegates for methods that get called by an IronPython script and that are not explicitly implemtented, yet. 我正在尝试设置C#代码来自动为IronPython脚本调用的方法创建虚拟或后备委托,而这些方法尚未明确实现。

Say there's a script that calls the non-static C# class method "MoveTo" which isn't implemented in the corresponding class yet. 假设有一个脚本调用了非静态C#类方法“ MoveTo”,该方法尚未在相应的类中实现。 Usually, in case it exists, it is added to the script's scope by creating a corresponding delegate instance that is given to the scope by a call to "SetVariable" with the name of the Method and the delegate instance. 通常,如果存在,则通过创建一个相应的委托实例将其添加到脚本的作用域中,该委托实例通过使用方法名称和委托实例的名称对“ SetVariable”的调用而赋予该作用域。 That works fine for methods that already are implemented. 这对于已经实现的方法很好用。

In case the method is not yet implemented the call shall not fail but instead be redirected to a dummy method that gracefully handles the call and pretends successful execution (which is to be considered uncritical in my specific case). 如果该方法尚未实现,则调用将不会失败,而应被重定向到可以妥善处理该调用并假装成功执行的虚拟方法(在我的特定情况下,这被认为是不重要的)。

The problem is: the methods invoked by the IronPython script have a wide range of signatures (actually they can have any possible kind of signature). 问题是:IronPython脚本调用的方法具有广泛的签名(实际上,它们可以具有任何可能的签名)。 Therefore I'd like to dynamically create a fallback delegate that gets the same signature of the called method and hence "catches" every call to not yet implemented methods. 因此,我想动态创建一个后备委托,该委托获得与被调用方法相同的签名,从而“捕获”对尚未实现的方法的每次调用。

Do you guys have any idea on how I can achieve this goal? 你们对我如何实现这个目标有任何想法吗?

You should be able to create a catch-all method that takes any number/type of args: 您应该能够创建采用任意数量/类型的args的包罗万象的方法:

object Fallback([ParamDictionary]IDictionary<object, object> kwargs, params object[] args) {
  return null; // or whatever
}

(Sadly, this is backwards from the normal Python way of writing a similar function: def foo(*args, **kwargs): .) (遗憾的是,这与编写类似功能的普通Python方法相反: def foo(*args, **kwargs):

If you don't use keywords args, you can drop that and just use params : 如果您不使用关键字args,则可以将其删除,而只需使用params

object Fallback(params object[] args) {
  return null; // or whatever
}

Then use .SetVariable("whatever", Fallback) to make it the fallback method. 然后使用.SetVariable("whatever", Fallback)使其成为fallback方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM