代码之家  ›  专栏  ›  技术社区  ›  juFo

.AsSpan阵列类型不匹配异常

  •  0
  • juFo  · 技术社区  · 4 年前

    斯梅博迪能解释为什么吗。当创建新的ReadOnlySpan时,AsSpan Throws一个ArrayTypeMismatchException没有?

    SomeMethod(Foo data) {
      IPoint[] tmp = (IPoint[])data.Points; // data.Points is OwnPoint[] (class OwnPoint : IPoint)
      //ReadOnlySpan<IPoint> pointsSpan = ((IPoint[])tmp).AsSpan(); //  System.ArrayTypeMismatchException: 'Attempted to access an element as a type incompatible with the array.'
      //ReadOnlySpan<IPoint> pointsSpan = tmp.AsSpan(); //  System.ArrayTypeMismatchException: 'Attempted to access an element as a type incompatible with the array.'
      ReadOnlySpan<IPoint> pointsSpan = new ReadOnlySpan<IPoint>(tmp);// works
      Bar(pointsSpan);
    }
    
    public void Bar(ReadOnlySpan<IPoint> pts) {
        // ...
    }
    

    1 回复  |  直到 4 年前
        1
  •  2
  •   JL0PD    4 年前

    这是一个类型安全的问题。正如@canton7所指出的那样 Span<T> ReadOnlySpan<T> 第一个是可变的,可以给它赋值。只要值具有相同的类型,一切都可以,但如果值具有不同的类型(例如。 ((object[])new string[1])[0] = 1 ArrayTypeMismatchException 所以数组中不可能有不同类型的值。

    Span<T>

    ReadOnlySpan<T> 不需要此支票,因为它是不可变的。