c# – 在泛型中实现算术?

是否可以在C#泛型中实现基本算法(至少是加法),就像你可以 with C++ templates一样?我已经尝试了一段时间来让它们起作用,但是C#不允许你多次声明相同的泛型类型,就像你可以使用模板一样.

广泛的谷歌搜索没有提供答案.

编辑:谢谢,但我正在寻找的是一种在编译时进行算术运算的方法,在泛型类型中嵌入像教会数字这样的东西.这就是为什么我把我做过的文章联系起来的原因.泛型类型的算术,而不是泛型类型实例的算术.

解决方法

遗憾的是,您无法对泛型类型使用算术运算
T Add(T a,T b)
{
    return a + b; // compiler error here
}

不会在c#中工作!

但是您可以创建自己的数字类型并重载运算符(算术相等和隐式,显式).这使您可以以一种非常自然的方式使用它们.但是,您无法使用泛型创建继承层次结构.您将不得不使用非泛型基类或接口.

我只是用矢量类型做到了.这是一个缩短版本:

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);
    }
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...