上級 › ArrayTypeMismatchException の原因と直し方 › パターン4
ArrayTypeMismatchException の原因と直し方
配列の共変性(string[]をobject[]として扱えること)を利用したコードで、実体の型と異なる要素を代入すると発生します。
1 class Book { public string Title; } 2 class Program { 3 static void Main(string[] args) { 4 Book[] books = new Book[2]; 5 object[] objs = books; 6 objs[0] = ________________________; ^ 7 System.Console.WriteLine(objs[0]); 8 } 9 }
Unhandled exception. System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array.
at Program.Main(String[] args) in Program.cs:line 6
空欄を埋めてビルドを通す
Book[]をobject[]として扱っても実体はBook[]のままなので、Book以外を入れると実行時に例外になります。
次の問題