不幸的是,您不能对泛型类型使用算术运算
T Add(T a, T b)
{
return a + b; // compiler error here
}
在 C# 中不起作用!
但是您可以创建自己的数字类型并重载运算符(算术、相等和implicit
, explicit
)。这让您可以以一种非常自然的方式与他们一起工作。但是,您无法使用泛型创建继承层次结构。您将必须使用非通用基类或接口。
我只是用向量类型来做的。这里有一个缩短的版本:
public class Vector
{
private const double Eps = 1e-7;
public Vector(double x, double y)
{
_x = x;
_y = y;
}
private double _x;
public double X
{
get { return _x; }
}
private double _y;
public double Y
{
get { return _y; }
}
public static Vector operator +(Vector a, Vector b)
{
return new Vector(a._x + b._x, a._y + b._y);
}
public static Vector operator *(double d, Vector v)
{
return new Vector(d * v._x, d * v._y);
}
public static bool operator ==(Vector a, Vector b)
{
if (ReferenceEquals(a, null)) {
return ReferenceEquals(b, null);
}
if (ReferenceEquals(b, null)) {
return false;
}
return Math.Abs(a._x - b._x) < Eps && Math.Abs(a._y - b._y) < Eps;
}
public static bool operator !=(Vector a, Vector b)
{
return !(a == b);
}
public static implicit operator Vector(double[] point)
{
return new Vector(point[0], point[1]);
}
public static implicit operator Vector(PointF point)
{
return new Vector(point.X, point.Y);
}
public override int GetHashCode()
{
return _x.GetHashCode() ^ _y.GetHashCode();
}
public override bool Equals(object obj)
{
var other = obj as Vector;
return other != null && Math.Abs(other._x - _x) < Eps && Math.Abs(other._y - _y) < Eps;
}
public override string ToString()
{
return String.Format("Vector({0:0.0000}, {1:0.0000})", _x, _y);
}
}
距离我回答这个问题已经过去十多年了,终于C# 11 功能 - 接口中的静态虚拟成员 https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members.NET 7 中引入允许我们做通用数学 https://learn.microsoft.com/en-us/dotnet/standard/generics/math以及许多其他事情。
接口现在可以声明静态工厂方法,而不限制我们在泛型上下文中使用无参数构造函数。