如何从IronPython脚本将Lambda表达式传递给C#构造函数? [英] How to pass a lambda expression to a C# constructor from an IronPython script?
问题描述
我正在将IronPython编写引擎集成到我的C#raytracer中,到目前为止,尽管我是Python的新手,但仍然很容易.但是,有一件事我需要帮助.我有一个C#类,它定义了一个像这样的构造函数:
I'm integrating an IronPython scritping engine into my C# raytracer which, so far, has been a breeze even though I'm completely new to Python. There is one particular thing, though, that I need help with. I have a C# class which defines a constructor like this:
public CameraAnimation(Action<Camera, float> animation)
在C#中,我将这样实例化:
In C#, I would instantiate this like so:
var camAnimation = new CameraAnimation((camera, time) => camera.Position += new Vector(1, 0, 0));
我不太清楚如何在IronPython中为Action对象进行类似的分配,所以Python语法看起来如何?
I can't quite figure out how to make a similar assignment for the Action object in IronPython, so how would the Python syntax look?
推荐答案
假设我解释了此权利,并且Action是泛型委托,则可以进行以下工作(包括我使用的存根).
Assuming I interpreted this right, and Action is a generic delegate, the below works (the stubs I used are included).
Python:
import clr
clr.AddReference("IronPythonDelegates")
import IronPythonDelegates
def camActionPy(camera, time):
print "Camera: " + str(camera) + ", time: " + str(time)
IronPythonDelegates.CameraAnimation(camActionPy);
CSharp:
namespace IronPythonDelegates
{
public class Camera{}
public class CameraAnimation
{
private System.Action<Camera, float> animation;
public CameraAnimation(System.Action<Camera, float> animation)
{
this.animation = animation;
this.animation(new Camera(), 1.5f);
}
}
}
我已更正以上内容以使用System.Action,并且不再需要显式反射.不过有点奇怪.由于某种原因,我可以构造一个用户创建的委托,例如:
I corrected the above to use System.Action, and it no longer requires explicit reflection. It's a bit weird though. For some reason, I could construct a user-created delegate like:
explicitTestAction = IronPythonDelegates.TestAction[IronPythonDelegates.Camera, System.Single](camActionPy);
IronPythonDelegates.CameraAnimation(explicitTestAction);
但不能通过System.Action来执行.例如.
but could not do so with System.Action. E.g. with
explicitSystemAction = System.Action[IronPythonDelegates.Camera, System.Single](camActionPy)
IronPythonDelegates.CameraAnimation(explicitSystemAction);
explicitSystemAction为空. TestAction的定义为:
explicitSystemAction is null. TestAction was just defined as:
public delegate void TestAction<T1, T2>(T1 one, T2 two);
但是幸运的是,做这件事很好:
But luckily either way it's fine to just do:
CameraAnimation(System.Action)
或
CameraAnimation(TestAction)
尽管出于某种原因,我不记得我第一次尝试时能正常工作...
though for some reason I don't remember that working when I first tried...
这篇关于如何从IronPython脚本将Lambda表达式传递给C#构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!