mercredi 13 juin 2018

Expression as function parameter for property and object type

I require a function which takes as parameter the following things:

  • The type of the object
  • Name of a specific property of the object

Currently I do it in a rather inconvenient and long way:

public static void Add<TEntity, TProperty>(TEntity e, Expression<Func<TProperty>> expression)
{
     var type = typeof(TEntity);
     var propertyName = ((MemberExpression) expression.Body).Member.Name;
}

Which results in a function call like this: Add(Foo, () => Foo.Bar);

However with that solution I have a couple problems:

  • It gets really long when I have a object like this: Add(Foo.Bar.Element.Type, () => Foo.Bar.Element.Type.Name) and looks quite ugly.
  • It isn't ensured that propertyName is a property of the object's type.
    • I actually don't do anything really with e so it's not used.

Is there a better solution to this?





Aucun commentaire:

Enregistrer un commentaire