我一直在尋找我的問題的解決方案很多小時沒有明確的答案,所以我不得不在這裏問。 這裏是我的示例代碼:通用方法 - 參數類型鑄造
class Geometry
{
public static Vector2 quadraticCurvePoint(Vector2 _p1, Vector2 _p2, Vector2 _p3, float _t)
{
return (1 - _t) * (1 - _t) * _p1 + 2 * (1 - _t) * _t * _p2 + _t * _t * _p3;
}
public static Vector3 quadraticCurvePoint(Vector3 _p1, Vector3 _p2, Vector3 _p3, float _t)
{
return (1 - _t) * (1 - _t) * _p1 + 2 * (1 - _t) * _t * _p2 + _t * _t * _p3;
}
public static T[] quadraticCurve<T>(T _p1, T _p2, T _p3, uint _q)
{
int points_count = (int)_q + 2;
T[] points = new T[points_count];
points[0] = _p1;
points[points_count - 1] = _p3;
float ti = 1/points_count;
float t;
for (int i = 1; i <= _q; i++)
{
t = ti * i;
points[i] = quadraticCurvePoint(_p1, _p2, _p3, t);
}
return points;
}
}
我想通過只類型Vector2和的Vector3,但我沒有任何想法如何使這個電話points[i] = quadraticCurvePoint(_p1, _p2, _p3, t);
becouse程序不知道是什麼類型的_p1 _p2 _p3工作。
Vector2和Vector3是OpenTK項目的一部分。他們被宣佈爲public struct Vector2 : IEquatable<Vector2>
並且有運營商實施。
當然,我可以簡單地爲Vector2和Vector3編寫這種方法的重載版本(重複代碼),但我不是BADASS程序員風格。
我知道我已經超負荷quadraticCurvePoint方法的擊打它會以同樣的方式作爲quadraticCurve方法來改善 - 如果可能的話......
可悲的是,你不能真正使用泛型在操作 - 不是在C#(你不能靜態操作進入接口約束泛型參數),所以你要麼必須使用兩個重載(我會這樣做)或使用一些令人討厭的反射/動態的東西 – Carsten
我想「糟糕的反射/動態」由於性能下降不值得實施。感謝您的時間。 – oozierus