上級 › ArrayTypeMismatchException の原因と直し方 › パターン2
ArrayTypeMismatchException の原因と直し方
配列の共変性(string[]をobject[]として扱えること)を利用したコードで、実体の型と異なる要素を代入すると発生します。
1 class Person { public string Name; } 2 class Program { 3 static void Main(string[] args) { 4 Person[] people = new Person[2]; 5 object[] objs = people; 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
空欄を埋めてビルドを通す
Person型の配列でも同じことが起きます。参照型どうしでも、配列の実体(ここではPerson[])と違う型を入れると実行時に検出されます。
次の問題