2

SQL からのデータを に格納し、それぞれをカスタム クラス インスタンスにDataTableマップするプロジェクトがあります。DataRow

プロパティ ( type )をループすると、型の推論はありません。RowsDataRowCollection

したがって、これは機能しません:

var dt = new DataTable();
foreach(var row in dt.Rows)
{
    int id = Int32.Parse(row.ItemArray[0].ToString());
    // doesn't compile
}

しかし、これは:

var dt = new DataTable();
foreach(DataRow row in dt.Rows)
{
    int id = Int32.Parse(row.ItemArray[0].ToString());
}

コンパイラが型を特定できないのはなぜrowですか? varを列挙する場合、キーワードは何か他のものを表すことができDataRowCollectionますか? データ行以外に、で列挙できるものはありDataRowCollectionますか?

それがあなたが明示的にする必要がある理由ですか?

4

1 に答える 1

4

Because DataRowCollection implements IEnumerable(via InternalDataCollectionBase) but not the generic, typed IEnumerable<T>. The class is simply too old.

By specifying the type in the foreach you're casting it implicitely.

于 2013-11-16T22:28:51.037 に答える