Skip to content

Instantly share code, notes, and snippets.

@mcintyre321
Created April 25, 2014 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcintyre321/11285405 to your computer and use it in GitHub Desktop.
Save mcintyre321/11285405 to your computer and use it in GitHub Desktop.
public class CsvFieldAttribute : Attribute
{
public CsvFieldAttribute()
{
Ignore = false;
}
public string Name { get; set; }
public int Index { get; set; }
public bool Ignore { get; set; }
}
public class CsvFieldAttributeBasedClassMap<T> : CsvClassMap<T>
{
public CsvFieldAttributeBasedClassMap()
{
var propertyInfosWithCsvAttributes = typeof(T).GetProperties()
.Select(pi => new { pi, att = pi.GetCustomAttributes(true).OfType<CsvFieldAttribute>().SingleOrDefault() })
.Where(pia => pia.att != null);
foreach (var pia in propertyInfosWithCsvAttributes)
{
if (pia.att.Ignore) continue;
Map(GetAccessorExpression(pia.pi)).Name(pia.att.Name ?? pia.pi.Name);
}
}
private static Expression<Func<T, object>> GetAccessorExpression(PropertyInfo prop)
{
var t = typeof(T);
if (prop.CanRead)
{
ParameterExpression lambdaParam = Expression.Parameter(t, "instance");
Expression bodyExpression;
MemberExpression memberAccessExpression = Expression.MakeMemberAccess(
Expression.Convert(lambdaParam, t), prop);
if (prop.PropertyType == typeof(object))
{
// Create lambda expression: (instance) => ((T)instance).Member
bodyExpression = memberAccessExpression;
}
else
{
// Create lambda expression: (instance) => (object)((T)instance).Member
bodyExpression = Expression.Convert(memberAccessExpression, typeof(object));
}
return Expression.Lambda<Func<T, object>>(bodyExpression, lambdaParam);
}
throw new InvalidOperationException("Cannot read property");
}
}
@mcintyre321
Copy link
Author

Jumping through hoops

@xraboteu
Copy link

xraboteu commented Jun 3, 2014

hi @mcintyre321
Could you show me how to use ?
regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment