开发者

Trying to create a "Fluent" type class using LINQ expressions

I'd like to do something as the follows, using lambdas and LINQ expressions in C#.

public class Foo
{
    private SomeEntity entity;
    public Foo(SomeEntity entity)
    {
        this.entity = entity;
        Bar(p => p.FirstName);
        Bar(p => p.SurName);
    }

    public void Bar(Expression> barExpression)
    {
        // What to do here?
    }
}

Every time I call Bar(), I'd like to dig into the Expression, and find out which property I am refer开发者_运维技巧ring to (e.g. FirstName or LastName), and also which SomeEntity object I am currently working with. I also need the value of the property (this is in fact the most important).

Eventually I'd like to extend Bar to do more than this, but this is as simple as I can "boil" my experiment.

Thanks!


public void Bar<T>(Expression<Func<SomeEntity, T>> expression)
{
    string name = ((MemberExpression)expression.Body).Member.Name;
}

should get the name; there is no instance in p => p.FirstName; but this.entity should give you what you want. The value is T value = expression.Compile()(entity)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜