如何将对象的日期类型转换为另一种类型?



这是我在代码下面写的一个注释错误。我不允许用另一种方式来做它应该是两个类,应该用这种方式来做。如果有人能帮助我,我会很感激的谢谢你

using System;
using MathLibrary;
namespace MathLibraryApp
{
class Program
{
static void Main(string[] args)
{
Vector v = new Vector();
Vector v1 = new Vector(4, 8, 12);
Vector v2 = new Vector(8,16,24);
Vector[] vectors = { v1, v2 };
Console.WriteLine(v.Add(vectors));
}
}
}
using System;
namespace MathLibrary
{
public class PointVectorBase
{
public PointVectorBase(double x=0 , double y=0 , double z=0 )
{
this.X = x;this.Y = y;this.Z = z;
}
protected virtual PointVectorBase CalculateSum(params Vector[] addends)
{
for (int i = 0; i < addends.Length; i++)
{
this.X = this.X + addends[i].X;
this.Y = this.Y + addends[i].Y;
this.Z = this.Z + addends[i].Z;
}
return this;
}
}
public class Vector : PointVectorBase
{
public Vector(double x = 0, double y = 0, double z = 0) : base(x, y, z){ }

public Vector Add(params Vector[] addends)
{
return this.CalculateSum(addends) ; 
//Cannot implicitly convert type MathLibrary.PointVectorBase to MathLibrary.Vector. An explicit conversion exists (are you missing a cast?)
}
}        
}

您可以像这样强制转换结果:

public Vector Add(params Vector[] addends)
{
return this.CalculateSum(addends) As Vector;
}

这很危险。不是所有的基向量都是向量,所以你可以得到一个空返回值。同样,在public class cat: animal的例子中,动物并不总是猫。

创建隐式转换更安全,但并不总是可能的:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators

方法CalculateSum返回值类型PointVectorBase。方法Add在Vector类中应该返回Vector

由于继承,你可以将CalculateSum的结果强制转换为Vector,因此它将返回this.CalculateSum(addends) as Vector;

在这种情况下,我不会选择继承。你只是在用方法扩展基类。

你的CalculateSum上的问题是你返回这个作为结果。这是一个奇怪的模式。要么使用void方法改变当前实例返回一个新实例(因此不修改当前实例)。我会选择后者。

如果你的问题是关于继承的,那么你举的这个例子不太好。

但是如果你想用另一种方式:

在你的例子中,我会选择扩展方法。这也是一个使用结构体的好例子。通过编写扩展方法,您可以使用额外的方法扩展Vector3 .

using System;
namespace MathLibrary
{
public struct Vector3
{
public double X;
public double Y;
public double Z;
public Vector3(double x=0 , double y=0 , double z=0 )
{
this.X = x;
this.Y = y;
this.Z = z;
}
public Vector3 CalculateSum(params Vector3[] addends)
{
var result = new Vector3();
for (int i = 0; i < addends.Length; i++)
{
result.X = result.X + addends[i].X;
result.Y = result.Y + addends[i].Y;
result.Z = result.Z + addends[i].Z;
}
return result;
}
}

public static class VectorExtensions
{
public static Vector3 Add(this Vector3 vector, params Vector3[] addends)
{
return vector.CalculateSum(addends); 
// the add should actually add to the current vector,
// which makes it less readable.. calculate sum and add is almost the same.
return vector.CalculateSum( 
new Vector3 [] { vector }
.Concat(addends)
.ToArray() );
}
}        
}

你的代码使用的函数式方法越多,奇怪的事情就越少。