[問題]Overload 三角函數

看板C_Sharp (C#)作者 (卡曼都)時間6年前 (2019/05/01 15:53), 6年前編輯推噓3(3010)
留言13則, 6人參與, 6年前最新討論串1/1
事情是這樣的 我寫了一個自定義的結構 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); } } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.115.66.73 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1556697197.A.B16.html

05/01 20:55, 6年前 , 1F
class helper isn't a language feature.
05/01 20:55, 1F
意思是Class Helper只能在特定狀況下使用?

05/01 22:57, 6年前 , 2F
查一下 extension method
05/01 22:57, 2F
Extension Method 之前有跟Class Helper一起查到 Extension Method 使用時要先引用,所以我才往Class Helper的方向查 目前看起來要這樣做似乎是沒有解的,謝謝各位的幫忙 ※ 編輯: commandoEX (140.115.66.73), 05/02/2019 10:33:19

05/02 20:52, 6年前 , 3F
System.Math 是靜態類,不能另外寫擴充方法,擴充方法是給
05/02 20:52, 3F

05/02 20:52, 6年前 , 4F
實體類用的
05/02 20:52, 4F

05/12 20:04, 6年前 , 5F
CLASS HELPER只是稱呼,它就是一個CLASS而已,沒超能力
05/12 20:04, 5F

05/15 00:46, 6年前 , 6F
C++ 有類似的功能 https://pse.is/HV3XQ
05/15 00:46, 6F

05/15 00:47, 6年前 , 7F
連結中的 class 能"直接"轉 int
05/15 00:47, 7F

05/15 00:56, 6年前 , 8F
但 C# 連 int x = 0.0; 都過不了,應該沒辦法自動轉型
05/15 00:56, 8F

05/15 22:17, 6年前 , 9F
隱式轉型是有的啊
05/15 22:17, 9F

05/17 16:44, 6年前 , 10F
int x = 0.0不行是會損失資訊的轉換需要explicit cast
05/17 16:44, 10F

05/17 16:50, 6年前 , 11F
然後C#就有上面那個類似的功能啊,user-defined conversion
05/17 16:50, 11F

05/17 16:51, 6年前 , 12F
static public implicit operator double(Angle value) {
05/17 16:51, 12F

05/17 16:51, 6年前 , 13F
return value.rad; }
05/17 16:51, 13F
文章代碼(AID): #1SoL1jiM (C_Sharp)
文章代碼(AID): #1SoL1jiM (C_Sharp)