C#でstringやfloatなどの型のリストをint型に変換する関数を作りたいと考え、下記のようなコードをこのサイトを参考に書きました。
実行するとnew_list[i].Add((TResult)(dynamic)list[i][j]);のところで'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' のハンドルされていない例外が System.Linq.Expressions.dll で発生しました: 'Cannot convert type 'string' to 'int''<例外のスタック トレースを評価できません>というエラーが吐かれました。
コメントアウトしているnew_list[i].Add(int.Parse((dynamic)list[i][j]));ではエラーが吐かれずキャストできたのになぜ下記の場合だとエラーが吐かれるのでしょうか?解決策とともに教えてください。
C#
1 public static void Main() 2 { 3 List<List<string>> test = new List<List<string>>(); 4 test.Add(new List<string>()); 5 test[0].Add("1"); 6 test[0].Add("5"); 7 test.Add(new List<string>()); 8 test[1].Add("2"); 9 test[1].Add("4"); 10 List<List<int>> test2 = List_Change<string, int>(test); 11 } 12 static List<List<TResult>> List_Change<T, TResult>(List<List<T>> list) 13 { 14 if (list.Count == 0) 15 { 16 return null; 17 } 18 List<List<TResult>> new_list = new List<List<TResult>>(); 19 for (int i = 0; i < list.Count; i++) 20 { 21 new_list.Add(new List<TResult>()); 22 for (int j = 0; j < list[i].Count; j++) 23 { 24 if (list[i][j] is not null) 25 { 26 new_list[i].Add((TResult)(dynamic)list[i][j]); 27 //new_list[i].Add(int.Parse((dynamic)list[i][j])); 28 //Null リテラルまたは Null の可能性がある値を Null 非許容型に変換しています。 29 } 30 } 31 } 32 return new_list; 33 }
ほとんど読んでないから知らないけど、TResult なのに int を使っているからじゃないですか?
List_Changeを呼び出す際にTResultをintに指定しているためTResultがintになると考えているのですが、この考えは間違っているでしょうか?
string→intのキャストができないってだけじゃないですか?
int.Parseでキャストするしかないのでしょうか?
前のスレッド https://teratail.com/questions/7142zse1e61um2 でやってることがメチャクチャと言われて逆ギレして回答に低評価を付けた人だよね? 答えをもらっても気に入らないとまた同じことをするのかな?
TypeDescriptor.GetConverterでTypeConverterを取得してコンバートするとか
ありがとうございます。やってみます
回答1件
あなたの回答
tips
プレビュー