如何检查数值是否为零

时间:2018-06-09 20:36:05

标签: c# generics math vector

这里我有一个应该对矢量建模的类的最小例子(用于线性代数计算)。它包含一个类型T,它将是一个整数或浮点类型(例如intdouble)。现在我想实现一个方法CheckIfZeroAt来检查某个条目是否包含零。问题是我想保留类型T变量,但据我所知,我无法告诉编译器我T是一个数字类型,其中可以使用类型转换。不幸的是,似乎还没有我可以限制T的数字类型的接口。

有没有优雅的方法来解决这个问题?

我提供了一些天真的方法,可以尝试将此方法实现为注释,但它们都不起作用。

class MyVector<T> // T is an integral or floating point type
{
    T[] vector;

    public MyVector(T[] array)
    {
        vector = array; //just a reference 
    }

    public bool CheckIfZeroAt(int i)
    {
        // return vector[0] == (T)0; //"Cast is redundant"
        // return vector[0] == 0; // Operator "==" cannot be applied to operands of type "T" and "int"
        // return vector[0] == 2 * vector[0]; // Operator "*" cannot be applied to operands of type "T" and "int"
    }

}

2 个答案:

答案 0 :(得分:2)

.NET中的数字类型有default of 0,所以只需检查它是否等于default(T)

public bool CheckIfZeroAt(int i)
{
    return vector[i].Equals(default(T));
}

小提琴here

汉斯在评论中指出,这不是最好的解决方案。看起来你应该一起跳过泛型,因为.NET中没有很多开箱即用的数字类型。

答案 1 :(得分:1)

您可以使用IConvertible。这允许所有数值类型。它还允许DateTime,字符串和位,但如果有人选择使用MyVector<bool>,你可以争论谁?它仍然是一个数字。

注意:由于浮点类型可能有错误,您可能希望允许容差。在我的例子中,公差为0.1。 (如果您的公差为0.5,则可以转换为int,而不是使用Math.Abs。)

class MyVector<T> where T : IConvertible
{
    T[] vector;

    public MyVector(T[] array)
    {
        vector = array; //just a reference 
    }

    public bool CheckIfZeroAt(int i, decimal tolerance = 0.1M)
    {
        return Math.Abs(Convert.ToDecimal(vector[i])) < tolerance;
    }

    public bool CheckIfZeroAt(int i)
    {
        return Convert.ToInt32(vector[i])) == 0;
    }

}
相关问题