I want to pass name of one of my class member as argument to method. Goal is to avoid sending plain string and forcing strongly type parameter. Here is the solution how to send and extract member name.
Watch it. We assume this lambda c => c.Id format. Any other will generate error in runtime.
if (expression.Body.NodeType == ExpressionType.Convert)
{
return ((expression.Body as UnaryExpression).Operand as MemberExpression).Member.Name;
}
else
{
return (expression.Body as MemberExpression).Member.Name;
}
...This was inspired with AutoMapper.
class MyClass
{
public int Id;
}
var d = new MyClass();
Build( c=>d.Id);
No comments:
Post a Comment