c# net 使用反射为对象赋值
1 public T Bson2T(MongoDB.Bson.BsonDocument bson) 2 { 3 T t = default(T); 4 5 //获取T类中的所有属性 6 PropertyInfo[] TpropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); 7 8 //用反射自动创建泛型对象 9 t=System.Activator.CreateInstance<T>(); 10 11 foreach (PropertyInfo pInfo in TpropertyInfo) 12 { 13 string pInfo_name=pInfo.Name; 14 15 //PropertyInfo bsonPropertyInfo= bson.GetType().GetProperty(pInfo_name); 16 17 //object bsonValue=bsonPropertyInfo.GetValue(bson,null); 18 19 object bsonValue = BsonGetValue(bson.ToString(), pInfo_name); 20 21 //给属性赋值 22 pInfo.SetValue((object)t,bsonValue,null); 23 } 24 return t; 25