上級 › ArrayTypeMismatchException の原因と直し方 › パターン1
ArrayTypeMismatchException の原因と直し方
配列の共変性(string[]をobject[]として扱えること)を利用したコードで、実体の型と異なる要素を代入すると発生します。
1 class Program { 2 static void Main(string[] args) { 3 string[] strs = new string[3]; 4 object[] objs = strs; 5 objs[0] = ____; ^ 6 System.Console.WriteLine(objs[0]); 7 } 8 }
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 5
空欄を埋めてビルドを通す
配列は共変性を持つため、string[]をobject[]として扱えてしまいます。しかし実体は変わらずstring配列なので、string以外を入れると実行時に例外になります。
次の問題