继续阅读 Stack Overflow 的另一个问题一个不同的用户,我想我会尝试代码,看看我能不能改进它。
我想澄清一些事情:
整个过程是一个学习练习,看看我能不能创造出像Dapper (这非常好) 不知道) IL排放东西。有了这个想法,我试图实施某种缓存,并假设反射对性能不利。
< (SqlDataReader行,List< PropertyInfo>属性,Dictionary< T>字符串,Int32>模式)其中T:new() { T item = new T(); if(schema!= null&& properties!= null&& row!= null) { foreach(属性中的var属性) { if(schema.ContainsKey(property.Name)) { //这可以吗? if(row [0] .GetType()== property.PropertyType) { property.SetValue(item,row [schema [property.Name]],null); { property.SetValue(item,Convert.ChangeType(row [schema [property.Name]],property.PropertyType),null); } } } } 退货项目; }
这个属性是通过这个方法传入的:
私人列表< PropertyInfo> GetPropertyInformation< T>() { List< PropertyInfo>性能; 类型_T = typeof(T); if(!PropertyCache.ContainsKey(_T)) { properties = _T.GetProperties()。ToList(); PropertyCache.Add(_T,properties); } else { properties = PropertyCache [_T]; } 返回属性;这是 PropertyCache private static Dictionary< Type,List< PropertyInfo>> PropertyCache {get;组; }
解决方案
Following on from another question on Stack Overflow by a different user, I thought I would try the code and see if I could improve it.
I would like clarification on a number of things:
The whole point is a learning exercise to see if I can create something like Dapper (which is very nice) but without the nasty looking (because i have no idea) IL emit stuff. With this is mind, I tried to implement some sort of caching with the assumtion that reflection is bad for perfomance.
The Code
private T CreateItemFromRow<T>(SqlDataReader row, List<PropertyInfo> properties, Dictionary<String, Int32> schema) where T : new() { T item = new T(); if (schema != null && properties != null && row != null) { foreach (var property in properties) { if (schema.ContainsKey(property.Name)) { // is this ok? if (row[0].GetType() == property.PropertyType) { property.SetValue(item, row[schema[property.Name]], null); } else { property.SetValue(item, Convert.ChangeType(row[schema[property.Name]], property.PropertyType), null); } } } } return item; }The properties is passed in from this method:
private List<PropertyInfo> GetPropertyInformation<T>() { List<PropertyInfo> properties; Type _T = typeof(T); if (!PropertyCache.ContainsKey(_T)) { properties = _T.GetProperties().ToList(); PropertyCache.Add(_T, properties); } else { properties = PropertyCache[_T]; } return properties; }And this is the declaration of PropertyCache
private static Dictionary<Type, List<PropertyInfo>> PropertyCache { get; set; }解决方案
更多推荐
反射和泛型的改进
发布评论