[問題]Overload 三角函數

作者: commandoEX (卡曼都)   2019-05-01 15:53:15
事情是這樣的
我寫了一個自定義的結構 Angle
儲存值是角度(degree),可以透過屬性讀徑度(rad)、圈(round)
、弧分(arcmin)和弧秒(arcsec)(這些屬性都是double)
現在想讓Angle跟一般的double一樣可以丟進三角函數中
像是Math.Sin(Angle)
而不是寫Math.sin(Angle.rad)
目前看到比較適合的解決方法是使用Class Helper
但是我寫了一個 MathHelper的Class
我試著寫 Math.Sin(Angle)是沒法編譯過的
如果是寫MathHelper.Sin(Angle)就沒問題
不過這樣我還不如就寫Math.Sin(Angle.rad)比較省事
是System.Math本來就不能用Class Helper去多載新函式?
還是我寫法不正確?
下面是程式碼
using System;
namespace UnitSystem
{
public struct Angle//角度
{
public const double R2D = 57.29577951308232087680;
public const double D2R = 0.01745329251994329577;
double _degree;
public double degree //角度
{
get => _degree;
set => _degree = value;
}
public double round //圈數
{
get { return this._degree / 360; }
set { _degree = value * 360; }
}
public double rad //徑度
{
get { return this._degree * D2R; }
set { _degree = value * R2D; }
}
public double arcmin //弧分
{
get { return this._degree * 60; }
set { _degree = value / 60; }
}
public double arcsec
{
get { return this._degree * 3600; }
set { _degree = value / 3600; }
}
public Angle(double value)
{
_degree = value*R2D;
}
}
public static class MathHelper
{
public static double Sin(Angle ang)
{
return Math.Sin(ang.rad);
}
public static double Cos(Angle ang)
{
return Math.Cos(ang.rad);
}
public static double Sinh(Angle ang)
{
return Math.Sinh(ang.rad);
}
public static double Cosh(Angle ang)
{
return Math.Cosh(ang.rad);
}
public static double Tan(Angle ang)
{
return Math.Tan(ang.rad);
}
public static double Tanh(Angle ang)
{
return Math.Tanh(ang.rad);
}
public static Angle aTan(Angle ang)
{
return Math.Atan(ang.rad);
}
}
}
作者: forewero (木日一)   2019-05-01 20:55:00
class helper isn't a language feature.
作者: YahooTaiwan (超可愛南西我老婆)   2019-05-01 22:57:00
查一下 extension method
作者: Litfal (Litfal)   2019-05-02 20:52:00
System.Math 是靜態類,不能另外寫擴充方法,擴充方法是給實體類用的
作者: forewero (木日一)   2019-05-12 20:04:00
CLASS HELPER只是稱呼,它就是一個CLASS而已,沒超能力
作者: WoodChen (木頭)   2019-05-15 00:46:00
C++ 有類似的功能 https://pse.is/HV3XQ連結中的 class 能"直接"轉 int但 C# 連 int x = 0.0; 都過不了,應該沒辦法自動轉型
作者: commandoEX (卡曼都)   2019-05-15 22:17:00
隱式轉型是有的啊
作者: ssccg (23)   2019-05-17 16:44:00
int x = 0.0不行是會損失資訊的轉換需要explicit cast然後C#就有上面那個類似的功能啊,user-defined conversionstatic public implicit operator double(Angle value) {return value.rad; }

Links booklink

Contact Us: admin [ a t ] ucptt.com