2009-04-28 22 views
5

我正在將一個IronPython掃描引擎整合到我的C#raytracer中,到目前爲止,儘管我對Python完全陌生,但仍然輕而易舉。有一件事情,但我需要幫助。我有一個C#類定義這樣一個構造函數:如何將一個lambda表達式從IronPython腳本傳遞給C#構造函數?

public CameraAnimation(Action<Camera, float> animation) 

在C#中,我將實例化這個像這樣:

var camAnimation = new CameraAnimation((camera, time) => camera.Position += new Vector(1, 0, 0)); 

我不能完全弄清楚如何使類似的任務IronPython中的Action對象,那麼Python語法怎麼看呢?

+2

你會列出一些*失敗*嘗試? 我相信我們都可以從你的失敗中學習。 (http://www.codinghorror.com/blog/archives/000576.html) – Sung 2009-04-28 23:40:52

+0

嘿,如果你堅持。我將C#代碼轉換爲Python的方法是將C#粘貼到.py文件並刪除東西,直到編譯完成。這大部分工作,但不幸的是我從一個相當明顯的觀點分心,我應該聲明一個函數並將其作爲參數傳遞。 – 2009-04-29 07:15:35

回答

2

假設我解釋了這個權利,並且Action是一個通用委託,下面的作品(包含我使用的存根)。

的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以上,並且它不再需要顯式的反射。雖然這有點奇怪。出於某種原因,我可以構建一個用戶創建的代表,如下所示:

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) 

但出於某種原因,我不記得,工作時我第一次嘗試...

相關問題