using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Reflection; namespace Extension { public static class Extension { public static IList<T> ToList<T>(this DataTable dt) { var lst = new List<T>(); var plist = new List<System.Reflection.PropertyInfo>(typeof(T).GetProperties()); foreach (DataRow item in dt.Rows) { T t = System.Activator.CreateInstance<T>(); for (int i = 0; i < dt.Columns.Count; i++) { PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName); if (info != null) { if (!Convert.IsDBNull(item[i])) { info.SetValue(t, item[i], null); } } }<br> lst.Add(t); } return lst; ///throw new NotImplementedException(); } } }
using System; using System.Text; using System.Reflection; using System.Collections; using System.Collections.Generic; namespace ConsoleApplication1 { public class Node { private int _id; private int _pid; private string _name; public Node() { } public Node(int id, int pid, string name) { _id = id; _pid = pid; _name = name; } public int ID { get { return _id; } set { _id = value; } } public int PID { get { return _pid; } set { _pid = value; } } public string Name { get { return _name; } set { _name = value; } } public override string ToString() { return "ID:" + _id + "\t" + "PID:" + _pid + "\t" + "Name:" + _name; } } class B { private object _dataSource; public object DataSource { get { return _dataSource; } set { _dataSource = value; } } //怎么遍历DataSource,取出ID,PID,Name属性值? public void RecursionList() { if (this._dataSource == null) return; if (this._dataSource is IEnumerable) { IEnumerable nodeList = (IEnumerable)this._dataSource; foreach (object node in nodeList) { PropertyInfo[] props = node.GetType().GetProperties(); foreach (System.Reflection.PropertyInfo prop in props) { object propValue = prop.GetValue(node, null); Console.WriteLine(string.Format("{0} = {1}", prop.Name, propValue)); } } } else if (this._dataSource is IEnumerable)//其他类型呢? { ... 此时,你想到什么呢?什么要做可使扩展性更好呢? } } } //应用举例 class Program { static void Main(string[] args) { List<Node> listTree = new List<Node>(); listTree.Add(new Node(0, 1, "北京")); listTree.Add(new Node(1, -1, "中国")); listTree.Add(new Node(2, 6, "莫斯科")); listTree.Add(new Node(3, 0, "海淀区")); listTree.Add(new Node(4, 0, "朝阳区")); listTree.Add(new Node(5, 3, "上地")); listTree.Add(new Node(6, -1, "俄罗斯")); listTree.Add(new Node(8, -1, "美国")); B newB = new B(); newB.DataSource = listTree; newB.RecursionList(); Console.Read(); } } }
浙公网安备 33010602011771号