作者commandoEX (卡曼都)
看板C_Sharp
标题[问题]Overload 三角函数
时间Wed May 1 15:53:15 2019
事情是这样的
我写了一个自定义的结构 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://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1556697197.A.B16.html
1F:→ forewero: class helper isn't a language feature. 05/01 20:55
意思是Class Helper只能在特定状况下使用?
2F:推 YahooTaiwan: 查一下 extension method 05/01 22:57
Extension Method 之前有跟Class Helper一起查到
Extension Method 使用时要先引用,所以我才往Class Helper的方向查
目前看起来要这样做似乎是没有解的,谢谢各位的帮忙
※ 编辑: commandoEX (140.115.66.73), 05/02/2019 10:33:19
3F:推 Litfal: System.Math 是静态类,不能另外写扩充方法,扩充方法是给 05/02 20:52
4F:→ Litfal: 实体类用的 05/02 20:52
5F:→ forewero: CLASS HELPER只是称呼,它就是一个CLASS而已,没超能力 05/12 20:04
7F:→ WoodChen: 连结中的 class 能"直接"转 int 05/15 00:47
8F:→ WoodChen: 但 C# 连 int x = 0.0; 都过不了,应该没办法自动转型 05/15 00:56
9F:→ commandoEX: 隐式转型是有的啊 05/15 22:17
10F:→ ssccg: int x = 0.0不行是会损失资讯的转换需要explicit cast 05/17 16:44
11F:→ ssccg: 然後C#就有上面那个类似的功能啊,user-defined conversion 05/17 16:50
12F:→ ssccg: static public implicit operator double(Angle value) { 05/17 16:51
13F:→ ssccg: return value.rad; } 05/17 16:51