上級 › ArrayTypeMismatchException の原因と直し方 › パターン3
ArrayTypeMismatchException の原因と直し方
配列の共変性(string[]をobject[]として扱えること)を利用したコードで、実体の型と異なる要素を代入すると発生します。
1 class Program { 2 static void Main(string[] args) { 3 string[] names = new string[2]; 4 object[] objs = names; 5 objs[1] = _____; ^ 6 System.Console.WriteLine(objs[1]); 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
空欄を埋めてビルドを通す
boolのような値型を入れても同じ例外になります。配列の実体の型(ここではstring[])だけが正解を決めます。
次の問題