我正在将一个 IronPython 脚本引擎集成到我的 C# raytracer 中,到目前为止,尽管我是 Python 的新手,但这是一件轻而易举的事。不过,有一件事我需要帮助。我有一个 C# 类,它定义了这样的构造函数:
public CameraAnimation(Action<Camera, float> animation)
在 C# 中,我会像这样实例化它:
var camAnimation = new CameraAnimation((camera, time) => camera.Position += new Vector(1, 0, 0));
我不太明白如何在 IronPython 中为 Action 对象进行类似的赋值,那么 Python 语法看起来如何?
最佳答案
假设我正确地解释了这一点,并且 Action 是一个通用委托(delegate),则以下工作正常(包括我使用的 stub )。
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,它不再需要显式反射。虽然有点奇怪。出于某种原因,我可以构造一个用户创建的委托(delegate),例如:
explicitTestAction = IronPythonDelegates.TestAction[IronPythonDelegates.Camera, System.Single](camActionPy);
IronPythonDelegates.CameraAnimation(explicitTestAction);
但无法使用 System.Action 这样做。例如。与
explicitSystemAction = System.Action[IronPythonDelegates.Camera, System.Single](camActionPy)
IronPythonDelegates.CameraAnimation(explicitSystemAction);
explicitSystemAction 为空。 TestAction 刚刚被定义为:
public delegate void TestAction<T1, T2>(T1 one, T2 two);
但幸运的是,无论哪种方式都可以:
CameraAnimation(System.Action)
或
CameraAnimation(TestAction)
尽管出于某种原因我不记得我第一次尝试时的工作...
关于c# - 如何从 IronPython 脚本将 lambda 表达式传递给 C# 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/799987/