前段时间比较郁闷,想做个通用的函数,从DbDataReader中读取所有数据。 上传一小段代码,也算是抛砖引玉了。 /// <summary> /// 通过映射取DbDataReader中的数据,只取最后一条数据 /// </summary> /// <param name="reader">DbDataReader实例()</param> /// <returns></returns> private Dictionary<string, object> DataReaderToDictionary(object reader) { Dictionary<string, object> valDic = new Dictionary<string, object>(); if (reader == null) return valDic; Type mytype = reader.GetType(); int fieldCnt = (int)mytype.InvokeMember("FieldCount", BindingFlags.GetProperty, null, reader, null); while (1 == 1) { bool next = (bool)mytype.InvokeMember("Read", BindingFlags.InvokeMethod, null, reader, null); if (next) { for (int i = 0; i < fieldCnt; i++) { object[] args = new object[] { i }; string key = (string)mytype.InvokeMember("GetName", BindingFlags.InvokeMethod, null, reader, args); object value = mytype.InvokeMember("GetValue", BindingFlags.InvokeMethod, null, reader, args); valDic.Add(key, value); } } else { break; } } return valDic; } 当然,在.NET 4.0中还可以使用dynamic来自动匹配类进行操作。