c# net 使用反射为对象赋值

时间:2023-03-09 15:28:14
c# net 使用反射为对象赋值
 public T Bson2T(MongoDB.Bson.BsonDocument bson)
{
T t = default(T); //获取T类中的所有属性
PropertyInfo[] TpropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); //用反射自动创建泛型对象
t=System.Activator.CreateInstance<T>(); foreach (PropertyInfo pInfo in TpropertyInfo)
{
string pInfo_name=pInfo.Name; //PropertyInfo bsonPropertyInfo= bson.GetType().GetProperty(pInfo_name); //object bsonValue=bsonPropertyInfo.GetValue(bson,null); object bsonValue = BsonGetValue(bson.ToString(), pInfo_name); //给属性赋值
pInfo.SetValue((object)t,bsonValue,null);
}
return t;

相关文章