5

我正在将 IronPython 脚本引擎集成到我的 C# 光线跟踪器中,尽管我对 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 语法看起来如何?

4

1 回答 1

2

假设我对此的解释是正确的,并且 Action 是一个通用委托,则以下工作(包括我使用的存根)。

Python:

import clr
clr.AddReference("IronPythonDelegates")

import IronPythonDelegates

def camActionPy(camera, time):
  print "Camera: " + str(camera) + ", time: " + str(time)

IronPythonDelegates.CameraAnimation(camActionPy);

夏普:

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,它不再需要显式反射。不过这有点奇怪。出于某种原因,我可以构造一个用户创建的委托,例如:

explicitTestAction = IronPythonDelegates.TestAction[IronPythonDelegates.Camera, System.Single](camActionPy);
IronPythonDelegates.CameraAnimation(explicitTestAction);

但不能使用 System.Action 这样做。例如与

explicitSystemAction = System.Action[IronPythonDelegates.Camera, System.Single](camActionPy)
IronPythonDelegates.CameraAnimation(explicitSystemAction);

显式系统操作为空。TestAction 刚刚定义为:

public delegate void TestAction<T1, T2>(T1 one, T2 two);

但幸运的是,无论哪种方式都可以:

CameraAnimation(System.Action) 

或者

CameraAnimation(TestAction)

虽然由于某种原因,我不记得我第一次尝试时的工作......

于 2009-04-28T23:03:51.090 回答