有人可以解釋為什么 .AsSpan 在創建新的 ReadOnlySpan 時不會引發 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) {
// ...
}
我錯過了什么?認為 .AsSpan 與創建一個新的一樣。
uj5u.com熱心網友回復:
這是一個型別安全的問題。正如@canton7 所指出的,Span<T>有型別檢查,而ReadOnlySpan<T>沒有。第一個是可變的,可以為其分配一些值。由于 long 值具有相同的型別,一切都可以,但是如果值具有不同的型別(例如((object[])new string[1])[0] = 1),則陣列賦值會拋出,ArrayTypeMismatchException因此在陣列中不可能有不同型別的值。
Span<T>在實體化時執行此檢查。我不知道這背后的動機,也許是性能。
ReadOnlySpan<T> 不需要此檢查,因為它不可變。
您可以在 Jeffrey Richter 通過 C# 的 Clr 中的第 16 章“陣列”中閱讀有關陣列轉換的更多資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/383547.html
上一篇:使處理程式通用
