Created
April 25, 2014 10:52
-
-
Save mcintyre321/11285405 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CsvFieldAttribute : Attribute | |
{ | |
public CsvFieldAttribute() | |
{ | |
Ignore = false; | |
} | |
public string Name { get; set; } | |
public int Index { get; set; } | |
public bool Ignore { get; set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Jumping through hoops