Generic Extension Method Ambiguity

后端 未结 6 1562
说谎
说谎 2020-12-09 11:34

I have two interfaces defined:

// IVector.cs
public interface IVector
{
    int Size { get; }

    float this[int index] { get; set; }
}

// IMatrix.cs
publi         


        
6条回答
  •  一向
    一向 (楼主)
    2020-12-09 12:16

    It is happening because generic constraints are not considered when evaluating whether two methods have the same signature. You are effectively defining two identical add methods.

    Try this approach:

    // VectorExtensions.cs
    public static T Add(this T vector, IVector value) where T : struct, IVector
    {
        var output = default(T);
    
        for (int i = 0; i < output.Size; i++)
            output[i] = vector[i] + value[i];
    
        return output;
    }
    
    // MatrixExtensions.cs
    public static T Add(this T matrix, IMatrix value) where T : struct, IMatrix
    {
        var output = default(T);
    
        for (int i = 0; i < output.Size; i++)
            for (int j = 0; j < output.Size; j++)
                output[i, j] = vector[i, j] + value[i, j];
    
        return output;
    }
    

提交回复
热议问题