在制作一个简单的C#物理模拟器时,我遇到了一些并发症并修复了所有这些模拟器。最后又出现了另一个问题;
“类型'Ball_and_gravity.Phyl.DSpeed'已经定义了一个名为'DSpeed'的成员,其参数类型相同”
它位于构造函数中。我不知道该怎么做。
public struct DSpeed : ISpeed, IAngleSpeed
{
public double Angle { get; set; }
public double Speed { get; set; }
public double XSpeed { get; set; }
public double YSpeed { get; set; }
public DSpeed(double ang, double sp)
{
Angle = ang;
Speed = sp;
XSpeed = Math.Sin(Angle) * Speed;
YSpeed = Math.Cos(Angle) * Speed;
}
public DSpeed(double xs, double ys)
{
XSpeed = xs;
YSpeed = ys;
DPoint p1 = new DPoint(0, 0);
DPoint p2 = new DPoint(XSpeed, YSpeed);
Speed = p1.GetDistance(p2);
Angle = Math.Atan2(XSpeed, YSpeed);
}
}
这里有什么问题?
答案 0 :(得分:0)
答案 1 :(得分:0)
建议不要使用浮动参数的解决方案,因为它会使结构的API对客户端代码非常不透明。即使你是你图书馆的唯一用户,你几乎肯定会在几个月后拔掉你的代码失败的原因,当你不小心打电话给错误的构造函数时。更不用说现有float和double两种类型的明显原因,即精度的差异。
您应该考虑引入两个命名的静态工厂方法,以明确您如何创建实例。 (你可能会提出比我下面选择的更好的名字)
public struct DSpeed
{
public double Angle { get; private set; }
public double Speed { get; private set; }
public double XSpeed { get; private set; }
public double YSpeed { get; private set; }
private DSpeed(double angle, double speed, double xspeed, double yspeed)
{
Angle = angle;
Speed = speed;
XSpeed = xspeed;
YSpeed = yspeed;
}
public static DSpeed FromAngle(double angle, double speed)
{
var xspeed = Math.Sin(angle) * speed;
var yspeed = Math.Cos(angle) * speed;
return new DSpeed(angle, speed, xspeed, yspeed);
}
public static DSpeed FromXY(double xspeed, double yspeed)
{
DPoint p1 = new DPoint(0, 0);
DPoint p2 = new DPoint(xspeed, yspeed);
var speed = p1.GetDistance(p2);
var angle = Math.Atan2(xspeed, yspeed);
return new DSpeed(angle, speed, xspeed, yspeed);
}
}
另外,我已将您的属性设置器设为私有,因为mutable structs are evil