中級 › Unable to cast object の原因と直し方 › パターン3
Unable to cast object の原因と直し方
object型に格納された値型(ボックス化)を、元の型と異なる型でアンボックスしようとすると発生します。
1 class Program { 2 static void Main(string[] args) { 3 object obj = true; 4 var n = (______)obj; ^ 5 System.Console.WriteLine(n); 6 } 7 }
Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.Boolean' to type 'System.Int32'.
at Program.Main(String[] args) in Program.cs:line 4
空欄を埋めてビルドを通す
boolとしてボックス化された値をintとして取り出すこともできません。C#のboolはintの別名ではありません。
次の問題