使用關鍵字動態在此方法中有效,如下所示,但我試圖找出一種不使用動態或var的方法。我想使用通用方法。有沒有可以使用的模式或轉換工具?在通用方法中將泛型轉換爲另一種類型
public static TAngle AngleBetween<TAngle>(Vector vector1, Vector vector2) where TAngle : IAngle
{
dynamic radians = (Radian)AngleBetween(vector1, vector2);
return (TAngle)radians;
}
這給了想要的結果,但它違反了Liskov的原則:
public static TAngle AngleBetween<TAngle>(Vector vector1, Vector vector2) where TAngle : IAngle
{
double result = AngleBetween(vector1, vector2);
Radian resultRadian = new Radian(result);
Degree testDegree = new Degree();
DegreeMinuteSecond testDMS = new DegreeMinuteSecond();
Gradian testGradian = new Gradian();
Turn testTurn = new Turn();
if (typeof(TAngle) == typeof(Degree))
{
testDegree = (Degree)resultRadian;
return (TAngle)(object)testDegree;
}
else if (typeof(TAngle) == typeof(DegreeMinuteSecond))
{
testDMS = (DegreeMinuteSecond)resultRadian;
return (TAngle)(object)testDMS;
}
else if (typeof(TAngle) == typeof(Gradian))
{
testGradian = (Gradian)resultRadian;
return (TAngle)(object)testGradian;
}
else if (typeof(TAngle) == typeof(Turn))
{
testTurn = (Turn)resultRadian;
return (TAngle)(object)testTurn;
}
else return (TAngle)(object)resultRadian;
}
有沒有人有什麼建議?
我想我們需要在這裏實現'Radian'和'IAngle'來回答這個問題。 – Jamiec
我懷疑編譯器可以保證'TAngle'永遠是一個'Radian'。如果該方法只能*使用'Radian',那麼爲什麼首先要使用它?只需返回一個'Radian'。 – David
是否有「TAngle」限制? – dymanoid