如何编写可能返回两种不同类型的方法?

Aym*_*udi 2 .net c# methods boxing return

我有一个名为Vector的类,我正在实现乘法运算符,这是我的实现:

public static Object operator *(Vector x, Vector y)
{

    //Possible return objects
    Matrix multiplicationResultMatrix;
    float multiplicationResultScalar = 0f;


    if (x.VectorType != y.VectorType)
    {
        if (x.Length == y.Length)
        {
            if ((x.VectorType == VectorType.Row) && (y.VectorType == VectorType.Column))
            {
                for (ulong i = 0; i < x.Length; i++)
                {
                    multiplicationResultScalar += x[i] * y[i];
                }
            }
            else
            {
                if ((x.VectorType == VectorType.Column) && (y.VectorType == VectorType.Row))
                {
                    multiplicationResultMatrix = new Matrix(x.Length);
                    for (ulong j = 0; j < x.Length; j++)
                    {
                        for (ulong i = 0; i < x.Length; i++)
                        {
                            multiplicationResultMatrix[i, j] += x[i] * y[j];
                        }
                    }
                }
            }
        }
        else
        {
            throw new ArithmeticException("Unhandled Arithmetic Exception, Multiplication of two vectors of different length is not allowed");
        }
    }
    else
    {
        throw new ArithmeticException("Unhandled Arithmetic Exception, Multiplicating vectors of the same type is not allowed");
    }

    //What should I return
    return ?
}
Run Code Online (Sandbox Code Playgroud)

我该如何定义返回类型?我考虑装箱,并在消费时取消装箱,但我认为这不是一个好的安全解决方案.

更新:

我还想过只返回一个矩阵对象,因为标量是1x1矩阵,问题是矩阵类得到了一些复杂的方法和特性,在1x1的情况下不能正常工作(这会迫使我添加一些代码),加上我想最小化和优化计算,我正在处理数百万的矩阵乘法.

das*_*ght 5

您应该避免根据输入参数的值更改返回类型(而不是在编译时已知的静态类型).这使得调用者可以完成方法工作的一部分,即确定返回的内容.

有两种解决方案:

  • 始终返回相同类型的对象 - 您的方法将返回NxN矩阵或1x1矩阵,具体取决于列或行是否为第一个,或者
  • 使用不同类型定义单独的方法 - 不使用运算符,make MultiplyRowColMultiplyColRow方法,返回不同类型的对象.

从技术上来讲,第一溶液是较好的,因为通过柱的行的乘法产生一个矩阵具有单个元件,而不是一个标量.