C# 某个自定义操作员?
我在导弹类的许多函数中使用了这种模式:C# 某个自定义操作员?,c#,operator-overloading,C#,Operator Overloading,我在导弹类的许多函数中使用了这种模式: class Missile { Vector2 position; public void Launch(Vector2 towards) { Launch(Geom.AngleBetween(position, towards)); } public void Launch(float angle) { ... DO THE THING } } 这让我写了很多函
class Missile
{
Vector2 position;
public void Launch(Vector2 towards)
{
Launch(Geom.AngleBetween(position, towards));
}
public void Launch(float angle)
{
... DO THE THING
}
}
这让我写了很多函数两次,我想知道是否有一种方法可以用某种自定义运算符只写一次?比如:
public virtual void LaunchTowards(Direction dir)
{
... DO THE THING
}
“方向”是一个具有自定义运算符强制转换的类,可自动将矢量2(朝向点)或浮点(角度)转换为浮点(角度)。问题是自定义运算符在C#中必须是静态的,因此我似乎无法使用从点转换为角度所需的位置变量。与其将向量转换为浮点,或者相反,不如将
方向
作为角度的包装,并允许从浮点到方向
和Vector2
到方向
的隐式转换
class Direction {
public float Angle { get; private set; }
public Direction(float angle) { this.Angle = angle; }
public implicit operator Direction(float angle) { return new Direction(angle); }
public implicit operator Direction(Vector2 vector) {
return new Direction(Math.Atan(vector.Y / vector.Y));
}
}
问题是,我无法使用此解决方案访问导弹的属性“位置”,我需要该属性才能从Vector2转换为float你不需要位置来将向量转换为float@Krucho你就不能使用atan函数吗?我已经在我的Geom中使用了atan。AngleBetween函数这里没有详细说明,我需要从点A->B计算角度的位置,而不是从(0;0)->A