gpt4 book ai didi

C#继承类型转换错误

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:55 26 4
gpt4 key购买 nike

我对 C# 中的继承有点陌生。我有两个类(class) Velocity.csPosition.cs从基类继承的 Vector.cs .我正在尝试创建一个名为 subtract() 的方法里面Vector.cs可以从 Velocity.cs 访问和 Position.cs .

这里是减法的代码。

     public Vector subtract(Vector v) {
double nx = this.x - v.x;
double ny = this.y - v.y;
double mag = Math.Sqrt(x * x + y * y);
double ang = Math.Atan2(y, x);
return new Vector(mag, ang);
}

定义 Velocity.cs 的代码类在下面。

class Velocity : Vector{

public Velocity(Position p1, Position p2, double vpref) : base(p1, p2) {
normalize();
scale(vpref);
}

public Velocity(double vmax) : base(new Random().NextDouble()*vmax, new Random().NextDouble()*2*Math.PI) {

}

public void change(Velocity v) {
x = v.x;
y = v.y;
magnitude = Math.Sqrt(x * x + y * y);
angle = Math.Atan2(y, x);
}

}

当我尝试在外部调用函数 subtract 时,是这样的:

        Velocity v1 = new Velocity(5);
Velocity v2 = new Velocity(7);
Velocity result = v1.subtract(v2);

我收到一条错误消息,提示无法在“速度”和“矢量”之间显式转换你是否忘记了转换?

所以我尝试了Velocity result = (Velocity)v1.subtract(v2);然而,这会导致以下错误:发生类型为“System.InvalidCastException”的未处理异常

我怎样才能重写这个函数来让它工作?我真的必须制作返回类型为 Vector 的函数的三个版本吗? VelocityPosition ?如果是这样,继承的意义何在?我可以将它们放在相关的类中。

注意:我知道速度类有点小,当时可能看起来毫无意义,我稍后会添加更多,我正在做一个项目。

最佳答案

我相信 Vector 类应该接受一个泛型类型参数,让它知道它的派生类的类型:

public class Vector<TImpl> where TImpl : Vector
{
public TImpl Subtract(TImpl v)
{
double nx = this.x - v.x;
double ny = this.y - v.y;
double mag = Math.Sqrt(x * x + y * y);
double ang = Math.Atan2(y, x);

return (TImpl)Activator.CreateInstance(typeof(TImpl), new object[] { mag, ang });
}
}

public class Velocity : Vector<Velocity>
{
}

顺便说一句,我觉得 Subtract 方法应该是一个扩展方法,一切看起来都不那么奇怪:

public static class VectorExtensions
{
public static TImpl Subtract<TImpl>(this TImpl vectorImpl, TImpl other)
where TImpl : Vector
{
double nx = this.x - v.x;
double ny = this.y - v.y;
double mag = Math.Sqrt(x * x + y * y);
double ang = Math.Atan2(y, x);

return (TImpl)Activator.CreateInstance(typeof(TImpl), new object[] { mag, ang });
}
}

...您将能够实现您的目标:

Velocity result = v1.Subtract(v2);

关于C#继承类型转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42053692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com