[英]Ignore properties with custom attribute set, using reflection
I have written a generic method that generates a collection of generic types from a Datatable. 我编写了一个泛型方法,从Datatable生成泛型类型的集合。 I have looked for different implementations, but most of them were performing very poorly performance wise when dealing with lots of properties and a lot of records. 我已经寻找了不同的实现,但是在处理大量属性和大量记录时,大多数都表现得非常糟糕。 This one is performing quite well so far. 到目前为止,这个表现相当不错。
I tried to improve the method by adding a custom attribute ( DataField ) on top of the properties, this way I could just include it on the properties and I can skip matching it up with the columns, or specify a custom name for the property that will match the datatable's column name. 我尝试通过在属性上添加自定义属性(DataField)来改进方法,这样我就可以将它包含在属性上,我可以跳过与列匹配,或者为属性指定自定义名称将匹配数据表的列名称。
I looked at the code and it looks like a huge mess now I'm really not proud of it and I want to have a nicer implementation. 我查看了代码,它看起来像一个巨大的混乱现在我真的不为它感到骄傲,我希望有一个更好的实现。 Can anyone give me some tips? 谁能给我一些提示? Would appreciate it a lot. 非常感激。
Tried to include comments not sure how much it helped. 试图包括评论不确定它有多大帮助。 Thank you, here is the code: 谢谢,这是代码:
private static void SetItemFromRow<T>(T item, DataRow row) where T : new()
{
// Get all properties with attributes.
PropertyInfo[] propWithAttributes = item.GetType().GetProperties().Where(x => Attribute.IsDefined
(x, typeof(DataField))).ToArray();
foreach (DataColumn col in row.Table.Columns)
{
// Find property that matches the column name.
PropertyInfo p = item.GetType().GetProperty(col.ColumnName);
bool ignoreProperty = false;
if (p != null)
{
// If no attribute exists set the property value. Break out from the loop to go to the next column (Property).
if (!propWithAttributes.Contains(p))
{
if (row[col] != DBNull.Value)
{
p.SetValue(item, row[col], null);
continue;
}
}
// If the property has a custom attribute then check if its ignore property is true. If so we break out from the loop and go to the next column (Property).
var attrs = p.GetCustomAttributes(typeof(DataField), false).ToArray() as DataField[]; ;
if (attrs != null)
foreach (var attr in attrs)
{
if (attr.Ignore)
ignoreProperty = true;
}
if (ignoreProperty) continue;
}
SetPropertyWithCustomName(item, propWithAttributes, row, col);
}
}
Now we have all properties set on the object that had a matching column name, also we skipped all the properties that we wanted to ignore. 现在我们在具有匹配列名的对象上设置了所有属性,我们也跳过了我们想要忽略的所有属性。 Final step is to set the properties that have a DataField attribute with the Name defined. 最后一步是设置具有定义了Name的DataField属性的属性。
private static void SetPropertyWithCustomName<T>(T item, PropertyInfo[] propWithAttributes, DataRow row, DataColumn col)
where T : new()
{
foreach (var prop in propWithAttributes)
{
// Get the attributes for the property.
var attrs = prop.GetCustomAttributes(typeof(DataField), false).ToArray() as DataField[];
bool match = false;
if (attrs != null)
{
foreach (var attr in attrs)
{
// Check if the column name matches the custom name on the property.
if (col.ColumnName == attr.Name)
{
var p = item.GetType().GetProperty(prop.Name);
if (row[col] != DBNull.Value)
{
p.SetValue(item, row[col], null);
match = true;
break;
}
}
}
if (match) break;
}
}
}
Here is a bit more readable version of your code (if I understand the intent correctly): 这是一个更易读的代码版本(如果我理解正确的意图):
private static readonly Dictionary<Type, DataFieldProperty[]> _propsCache = new Dictionary<Type, DataFieldProperty[]>();
private static DataFieldProperty[] GetProperties(Type type) {
lock (_propsCache) {
if (!_propsCache.ContainsKey(type)) {
var result = new List<DataFieldProperty>();
foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) {
var attr = prop.GetCustomAttribute<DataField>();
result.Add(new DataFieldProperty {
Name = attr?.Name ?? prop.Name,
Ignore = attr?.Ignore ?? false,
Property = prop
});
}
_propsCache.Add(type, result.ToArray());
}
return _propsCache[type];
}
}
private class DataFieldProperty {
public string Name { get; set; }
public PropertyInfo Property { get; set; }
public bool Ignore { get; set; }
}
private static void SetItemFromRow<T>(T item, DataRow row) where T : new() {
// Get all properties with attributes.
var props = GetProperties(item.GetType());
foreach (DataColumn col in row.Table.Columns) {
// Find property that matches the column name.
var p = props.FirstOrDefault(c => c.Name == col.ColumnName && !c.Ignore);
if (p != null) {
if (row[col] != DBNull.Value) {
p.Property.SetValue(item, row[col], null);
}
}
}
}
Note that I didn't actually run it (but verified it compiles). 请注意,我实际上没有运行它(但验证它编译)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.