我希望能夠隱式轉換兩個不兼容的類。我可以爲兩個不直接控制的類添加隱式轉換嗎?
其中一個類是Microsoft.Xna.Framework.Vector3
,另一個類只是在F#項目中使用的Vector
類。我正在用XNA編寫C#遊戲的3D遊戲,雖然它是用3D繪製的,但遊戲玩法只發生在兩個維度(這是鳥瞰)。的F#類需要物理的護理,使用2D矢量:
type Vector<'t when 't :> SuperUnit<'t>> =
| Cartesian of 't * 't
| Polar of 't * float
member this.magnitude =
match this with
| Cartesian(x, y) -> x.newValue(sqrt (x.units ** 2.0 + y.units ** 2.0))
| Polar(m, _) -> m.newValue(m.units)
member this.direction =
match this with
| Cartesian(x, y) -> tan(y.units/x.units)
| Polar(_, d) -> d
member this.x =
match this with
| Cartesian(x, _) -> x
| Polar(m, d) -> m.newValue(m.units * cos(d))
member this.y =
match this with
| Cartesian(_, y) -> y
| Polar(m, d) -> m.newValue(m.units * sin(d))
該載體類利用由物理項目,這需要測量的天然F#單位和團體在一起(單位使用的單位系統的距離,時間,質量等)。
但是XNA使用自己的Vector3
類。我想添加從F#Vector
到XNA Vector3
的隱式轉換,其中其中遊戲玩法發生的兩個方面,哪個軸是「向上」等等。它會很簡單,只是Vector v -> new Vector3(v.x, v.y, 0)
什麼的。
我不知道如何去做。我無法在F#中添加隱式轉換,因爲類型系統(正確)不允許它。我無法將它添加到Vector3類中,因爲它是XNA庫的一部分。至於我可以告訴我不能使用擴展方法:
class CsToFs
{
public static implicit operator Vector3(this Vector<Distance> v)
{
//...
}
}
是在this
關鍵字錯誤,並
class CsToFs
{
public static implicit operator Vector3(Vector<Distance> v)
{
return new Vector3((float)v.x.units, (float)v.y.units, 0);
}
public static void test()
{
var v = Vector<Distance>.NewCartesian(Distance.Meters(0), Distance.Meters(0));
Vector3 a;
a = v;
}
}
是a = v;
錯誤(不能隱式轉換... )。
有沒有辦法做到這一點,而無法將劇組放在任何一個類中?作爲最後的手段,我可以open Microsoft.Xna.Framework
並在F#中進行轉換,但這對我來說似乎是錯誤的 - 物理庫不應該知道或關心我用什麼框架編寫遊戲。
不能相信我沒有想到這個,即使它幾乎正是我想要的。 – 2011-04-02 23:46:31