Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class InputMapper<TSource>
- {
- private List<InputMapping> mappings = new List<InputMapping>();
- public void Map<TProperty>(object input, Expression<Func<TSource, TProperty>> projection, string errorMessage)
- {
- mappings.Add(new InputMapping<TSource, TProperty>
- {
- Input = input,
- Projection = projection,
- ErrorMessage = errorMessage
- });
- }
- public TSource Create()
- {
- var instance = Activator.CreateInstance<TSource>();
- foreach (var mapping in mappings)
- {
- if (!mapping.Apply(instance))
- {
- throw new Exception(mapping.ErrorMessage);
- }
- }
- return instance;
- }
- }
- abstract class InputMapping
- {
- public object Input { get; set; }
- public string ErrorMessage { get; set; }
- public abstract bool Apply(object target);
- }
- class InputMapping<TSource, TProperty> : InputMapping
- {
- public Expression<Func<TSource, TProperty>> Projection { get; set; }
- public override bool Apply(object target)
- {
- if (!target.GetType().Equals(typeof(TSource)))
- {
- return false;
- }
- var lambda = Projection as LambdaExpression;
- if (lambda == null)
- {
- return false;
- }
- MemberExpression exp = lambda.Body as MemberExpression;
- if (exp == null)
- {
- return false;
- }
- PropertyInfo prop = exp.Member as PropertyInfo;
- if (prop == null)
- {
- return false;
- }
- if (!prop.CanWrite || prop.GetIndexParameters().Length > 0)
- {
- return false;
- }
- prop.SetValue(target, Convert.ChangeType(Input, typeof(TProperty)), null);
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement