Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created September 12, 2022 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ufcpp/955192be315806e70434e90d41fba150 to your computer and use it in GitHub Desktop.
Save ufcpp/955192be315806e70434e90d41fba150 to your computer and use it in GitHub Desktop.
久々にミスった。
// ↓.NET 的に許されていはいるものの、 items[0] = new Base(); が例外を起こすので今となってはあんまり使いたくない機能。
// 意図的に使うことはめったにないものの…
Base[] items1 = new Derived[1];
// ↓これはミスってやっちゃうことが…
// (左辺からの型推論はせず、初期化側から推論して Derived[] になる。)
Base[] items2 = new[] { new Derived() };
// items2[0] = new Base(); が問題を起こすのはまあ、有名として、
// new Span<T>(), AsSpan<T>() は呼んだ時点で例外らしい。
Span<Base> span = items2; // ここで ArrayTypeMismatchException が飛ぶ。
class Base { }
class Derived : Base { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment